0

I have a question. Why does the output for the 2 pointers different? I did not assign pointees to either but one does not return NULL while one returns NULL.

typedef struct node
{
    bool word;
    struct node* children[27];
}
node;

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

    printf("%p %p\n", header.children[1], header_2->children[1]);
}

OUTPUT: 0xbfba76d4 (nil). Shouldn't both be NULL? Thanks a lot!

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631

2 Answers2

0

Consider the following case:

int i;
int *j = malloc(sizeof(int));
printf("%d, %d", i, (*j)) ;

(You cannot guarantee that i=0 and *j=0 because a memory has been allocated to both but their values may be garbage value which is what that memory location had previously occupied)

In order to have a defined value, always initialize the allocation/initialization with 0.

node a;                              // Everything default-initialized

void foo()
{
    static nodeb;                   // Everything default-initialized

    node c;                         // Nothing initialized
    node d = { 0 };                 // Everything default-initialized
    node *p = malloc(sizeof(*p));    // Nothing initialized
    node *q = calloc(1, sizeof(*q)); // Everything zero-initialized
}
  • Everything default initialized means they are initialized with the default value which is zero.
  • Nothing initialized means they will persist the value of the location which may be a garbage value or zero.

Ref link: C struct with pointers initialization

Community
  • 1
  • 1
thepace
  • 2,221
  • 1
  • 13
  • 21
  • Your answer uses C++-specific code. The code in the question is valid either as C or as C++; stylistically, it appears to be C. The OP didn't specify a language tag; I added the "c" tag. You might want to edit your answer so it's valid C (just use `printf` rather than `cout << ...`). – Keith Thompson Jan 09 '15 at 18:26
  • It is indeed C but I can understand C++ to a certain extent too! Thanks so much for clearing things up! – user4437880 Jan 09 '15 at 18:38
  • @thepace: You missed the tag because it wasn't there yet; I added it after you posted your answer. – Keith Thompson Jan 09 '15 at 19:27
0

this line: node header;

will contain whatever trash happens to be on the stack at the address of the header variable.

this line: node* header_2 = malloc(sizeof(node));

will contain whatever is returned by the call to malloc

(which, if malloc is successful will be a pointer to somewhere in the 'heap' and if malloc fails will be NULL)

user3629249
  • 16,402
  • 1
  • 16
  • 17