Alfonso Morra wrote on 24/09/05 :
> Hi,
>
> I have the ff data types :
>
> typedef enum {
> VAL_LONG ,
> VAL_DOUBLE ,
> VAL_STRING ,
> VAL_DATASET
> }ValueTypeEnum ;
>
> typedef union {
> long lval ;
> double fval ;
> char* sval ;
> void* ptr ;
> } Value ;
>
> typedef struct {
> int magic ;
> int version ;
> }Header ;
>
> typedef struct {
> char label[20] ;
> id int ;
> }Key ;
>
> typedef struct {
> Header *hdr ;
> char *subject ;
> int subject_len ;
> Key key ;
> ValueTypeEnum type ;
> Value value ;
> int text_len ;
> int size ;
> }MotherStruct ;
>
> If I have a variable declared as ff:
>
> MotherStruct *pMS = calloc(1,sizeof(MotherStruct*)) ;
Not portable. Filling the memory block with all bits to zero may
produce an unexpected behaviour. For example, a pointer with all bits
to zero is not necessarely a NULL pointer. It's
implementation-dependent. Same problem with floating points. Please
read archives, this subject has been discussed ad-nauseam...
> 1). Do I have to allocate memory seperately for each individual nested
> pointer in the structure (i.e. hdr and subject?). I guess the answer is yes -
> but I just need to be sure (see question 3 below).
Yes. There is no magic in C. all mis explicit. If you want magic, build
you own 'constructor' function. A common approach.
> 2). How do I calculate the size (in bytes) of the structure MotherStruct - so
> that I can use a function like memcpy to copy this memory block to another
> memory block ?
You don't. The = operator does the job. Of course, the pointed blocks
are not copied. Once again, if you want magic, build your own 'copy'
function. If you insist (not typed pointers in a generic context), the
sizeof operator returns the sizeof of any typed object.
BTW, I feel a sort of design error... do you really need to copy such a
structure ? As far as possible, memory copies are to be avoided...
> 3). Finally, (this is related in a way to the first question). If I just call
> free on pMS is all the memory that was allocated freed (is the answer the
> same if I have to issue seperate calls to allocate memory to the individual
> nested pointers - i.e. will a single call to free(pMs) free any memory
> allocated to pointers nested within the structure - OR do I need to free each
> of the nested pointers before finally freeing the memory block pointed to by
> pMS ?
All what have been allocated must be explicitely freed. Once again, if
you want magic, build your own 'destructor'.
The RTL (standard C run-time library) uses such a approach with the
FILE object :
- Constructor : fopen()
- Destructor : fclose()
a good source of inspiration...
--
Emmanuel
The C-FAQ:
http://www.eskimo.com/~scs/C-faq/faq.html
The C-library:
http://www.dinkumware.com/refxc.html
"Clearly your code does not meet the original spec."
"You are sentenced to 30 lashes with a wet noodle."
-- Jerry Coffin in a.l.c.c++