Do I need to initiallize(set to 0) memory after calling realloc?

Chris picture Chris · Jan 11, 2014 · Viewed 9.6k times · Source

I need to implement a simple dynamic array of pointers to a typedef'ed pointer.
Using realloc each time it's requested by the user, the array size will grow by sizeof(pointer).
So what I have is this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void* node;

void printmem(node* a, int c) {
    int i;
    for (i = 0; i < c; ++i)
    {
        printf("%d\t\t%p\n", i, a[i]);
    }
}

int main(void) {
    node* nodes = NULL;
    int i = 0, count = 20;

    for (i = 0; i < count; ++i)
    {
        nodes = realloc(nodes, sizeof(node));
    }
    printf("Done reallocating\n");
    printmem(nodes, i);
    // free(a);
    return 0;   
}

This gives the following output:

Done reallocating
0       (nil)
1       (nil)
2       (nil)
3       0x20fe1
4       (nil)
5       (nil)
6       (nil)
7       (nil)
8       (nil)
9       (nil)
10      (nil)
11      (nil)
12      (nil)
13      (nil)
14      (nil)
15      (nil)
16      (nil)
17      (nil)
18      (nil)
19      (nil)

I am concerned about the 3rd element, and its content.
That's why I am asking if I should set to 0 the memory after a new realloc.

Edit:
So, as pointed to the standard of C, by H2CO3, the new call to realloc, is:
nodes = realloc(nodes, (i+1)*sizeof(node));
And after that for initiallization, I did this: nodes[i] = NULL
which also worked just fine.

Edit2:
I have this now:

int main(void) {
    node* nodes = NULL;
    int i = 0, count = 20;

    for (i = 0; i < count; ++i)
    {
        nodes = realloc(nodes, (i+1)*sizeof(node));
        nodes[i] = NULL;
        if (i == 1) {
            nodes[i] = &count;
        }
    }
    printf("Done reallocating\n");
    printmem(nodes, i);
    printf("\t*nodes[1] == %d\n", *(int*)nodes[1]);
    printf("\tAddress of count is %p\n", &count);
    // free(a);
    return 0;   
}

Answer

Ed S. picture Ed S. · Jan 11, 2014

Well, it all depends. Do you require that the memory be initialized to 0? If not, then no, you don't need to do anything. Just as is the case with malloc, realloc doesn't perform any initialization. Any memory past the memory that was present in the original block is left uninitialized.