zeroing structure of char pointers

A

Aaron Walker

I was just wondering, if I have:

struct my_struct {
char *str1;
char *str2;
};

and then elsewhere do:

struct my_struct *ms = calloc(1, sizeof(struct my_struct));

Would that be the same as doing:

struct my_struct *ms = malloc(sizeof(struct my_struct));
ms->str1 = ms->str2 = NULL;


Thanks,
Aaron
 
A

Arthur J. O'Dwyer

I was just wondering, if I have:

struct my_struct {
char *str1;
char *str2;
};

and then elsewhere do:

struct my_struct *ms = calloc(1, sizeof(struct my_struct));

Would that be the same as doing:

struct my_struct *ms = malloc(sizeof(struct my_struct));
ms->str1 = ms->str2 = NULL;

Nope. In the first case, you're allocating memory for a struct,
and then 'calloc' is initializing all the allocated bits to zero.
In the second case, you're allocating memory for a struct, and then
initializing ms->str1 to NULL and ms->str2 to NULL.
So there are two key differences:

1. NULL != all bits zero. This is a FAQ.
http://www.eskimo.com/~scs/C-faq/q7.31.html
As a corollary, structs may have padding bits, which would not get
initialized to anything in the second case (but would receive 'zero'
bits in the first, along with every other bit). This is also a FAQ,
but is much less relevant to your actual problem.

2. The second snippet invokes undefined behavior if 'malloc'
returns NULL (failure to allocate enough memory). The first snippet
is perfectly well-defined in all cases -- but, as above, it won't do
what you're expecting it to do.

Read the FAQ; there's lots of important stuff there.

HTH,
-Arthur
 
M

Mac

I was just wondering, if I have:

struct my_struct {
char *str1;
char *str2;
};

and then elsewhere do:

struct my_struct *ms = calloc(1, sizeof(struct my_struct));

Would that be the same as doing:

struct my_struct *ms = malloc(sizeof(struct my_struct));
ms->str1 = ms->str2 = NULL;

Not necessarily. The portable solution is to assign NULL to all pointers.
Thanks,
Aaron

Mac
 
E

Emmanuel Delahaye

Not necessarily. The portable solution is to assign NULL to all pointers.

Of course, you meant 'a' portable solution. Here is an alternative :

struct my_struct *ms = malloc (sizeof *ms);

if (ms != NULL)
{
/* clear the struct */
static const struct my_struct z = {0};
*ms = z;

/* the rest of the code... */
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top