Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

c - 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%p
", 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
");
    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
");
    printmem(nodes, i);
    printf("*nodes[1] == %d
", *(int*)nodes[1]);
    printf("Address of count is %p
", &count);
    // free(a);
    return 0;   
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...