2

If I set a pointer to a struct to point to a block of memory via malloc, will all the members initialize to their respective default values? Such as int's to 0 and pointer's to NULL? I'm seeing that they do based on this sample code I wrote, so I just wanted someone to please confirm my understanding. Thanks for the input.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct node
{
    bool value;
    struct node* next[5];
}
node;

int main(void)
{
    node* tNode = malloc(sizeof(node));

    printf("value = %i\n", tNode->value);

    for (int i = 0; i < 5; i++)
    {
        if (tNode->next[i] == NULL)
            printf("next[%i] = %p\n", i, tNode->next[i]);
    }
}
de3z1e
  • 411
  • 4
  • 8
  • Thanks for everyone's input. I get that the pointer pointing to the new block of memory via malloc will not necessarily initialize to NULL, however my question is why do the elements in the member pointer array struct node* next[5] point to NULL? They have not been malloc'd. I guess my question would be, will a pointer variable (that is a member of a struct) always point to NULL before it is malloc'd? – de3z1e Jan 19 '15 at 03:59

3 Answers3

7

malloc() function never initializes the memory region. You have to use calloc() to specifically initialize a memory region to zeros. The reason you see initialized memory is explained here.

Community
  • 1
  • 1
sumithdev
  • 331
  • 1
  • 8
  • Use `calloc` *or set things to zero yourself* (either by setting fields individually, or by using `memset`) – user253751 Jan 19 '15 at 03:38
4

No. malloc never initializes the allocated memory. From the man page:

The memory is not initialized.

From the C standard, 7.20.3.3 The malloc function:

The malloc function allocates space for an object ... whose value is indeterminate.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

You can use static const keywords to set the member variables of your struct.

#include

struct rabi 
{
int i;
float f;
char c;
int *p; 
};
int main ( void )
{

static const struct rabi enpty_struct;
struct rabi shaw = enpty_struct, shankar = enpty_struct;


printf ( "\n i = %d", shaw.i );
printf ( "\n f = %f", shaw.f );
printf ( "\n c = %d", shaw.c );
printf ( "\n p = %d",(shaw.p) );


printf ( "\n i = %d", shankar.i );
printf ( "\n f = %f", shankar.f );
printf ( "\n c = %d", shankar.c );
printf ( "\n p = %d",(shankar.p) );
return ( 0 );
}



Output:

 i = 0
 f = 0.000000
 c = 0
 p = 0

 i = 0
 f = 0.000000
 c = 0
 p = 0
rabi shaw
  • 441
  • 1
  • 3
  • 14