调用 realloc 后是否需要初始化(设置为 0)内存? [英] Do I need to initiallize(set to 0) memory after calling realloc?

查看:39
本文介绍了调用 realloc 后是否需要初始化(设置为 0)内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个简单的动态指针数组,指向一个类型定义的指针.
每次用户请求时使用 realloc,数组大小将增加 sizeof(pointer).
所以我所拥有的是:

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;   
}

这给出了以下输出:

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)

我关心第三个元素及其内容.
这就是为什么我问我是否应该在新的重新分配后将内存设置为 0.

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.


因此,正如 C 的标准所指出的,通过 H2CO3,对 realloc 的新调用是:
nodes = realloc(nodes, (i+1)*sizeof(node));
在初始化之后,我这样做了:nodes[i] = NULL
这也工作得很好.


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;   
}

推荐答案

好吧,这完全取决于.您是否要求将内存初始化为 0?如果没有,那么不,你不需要做任何事情.与 malloc 的情况一样,realloc 不执行任何初始化.任何超出原始块中内存的内存都未初始化.

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.

这篇关于调用 realloc 后是否需要初始化(设置为 0)内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆