Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;   
}
like image 531
Chris Avatar asked Dec 09 '22 10:12

Chris


1 Answers

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.

like image 197
Ed S. Avatar answered Dec 11 '22 11:12

Ed S.