Re: Best way of Allocating and Deallocating memory
On Sep 17, 1:29 pm, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2007-09-17 12:48, Amit_Basnak wrote:
I have two structures as below
typedef struct {
long_int length;
char data[1];
} CI_STRUCT_DATA;
Notice that char data[1] is an array with one element, which
is the same as a normal char, then later your treat it as if
it was a char pointer.
Actually, he treats it as if it were a char[], a VLA. C++ (like
C90) doesn't have VLA's, and the above isn't a VLA in C99
either; he'd have to declare it "char data[];".
This is *very* bad, a char is 1 byte, a pointer is probably at
least 4 times that big, which means that you are trying to
write to memory outside of the struct. Also, you use a type
long_int, is that a typedef for a long? Further more, typedefs
with the structs are not needed in C++ and can be omitted.
Lastly, all upper-case names are generally reserved for
macros.
struct CiData {
long length;
char* data;
};
Note that length should probably be unsigned, and a normal int
is probably enough.
Unsigned is a bit special in C++, and in general, plain int
should be used as the default type, unless there are overriding
reasons for some other type. (One overriding reason is that
comparisons between signed and unsigned are sometimes confusing,
so if unsigned is imposed on you elsewhere---e.g. by the STL---,
then you probably want to conform to the type used there---in
the case of the STL, size_t.)
In C++, of course, the correct way to write the above would be:
typedef std::vector< char > CiData ;
Which solves all of his problems in one fell swoop.
[...]
Please suggest me any improvements in memory allocations if any
Using new:
CiMsg msg_details;
msg_details.MSG_DATA = new CiData;
msg_details.MSG_DATA->data = new char[strlen(ptr_msg_details) + 1];
strcpy(msg_details.MSG_DATA->data, ptr_msg_details);
To free the memory use delete:
delete msg_details.MSG_DATA->data;
detele msg_details.MSG_DATA;
An even better solution would be to use std::string
Or std::vector< char >. I sort of suspect that he's trying to
format a message for transmission. In such cases, the
functionality of std::vector< char > is often more appropriate
than that of std::string.
But of course, I'm just guessing as to the use. All I really
know is that the code he posted looks more like C than C++, and
that it has undefined behavior in both languages.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34