realloc 会对旧指针做什么 [英] what will realloc do to the old pointer

查看:35
本文介绍了realloc 会对旧指针做什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 realloc 函数的问题.应用 realloc 函数后旧指针的内容会改变吗?代码是

I have a question about the realloc function. Will the content of old pointer be changed after apply realloc function? The code is

main () {
    int *a, *b, i;

    a = calloc(5, sizeof(int));
    for (i = 0; i < 5; i++)
            a[i] = 1;
    for (i = 0; i < 5; i++)
            printf("%d", a[i]);
    printf("\n%p\n", a);

    b = realloc(a, 200000 * sizeof(int));
    if(b == NULL)
            printf("error\n");
    for (i = 0; i < 5; i++)
            printf("%d", a[i]);
    printf("\n");
    for (i = 0; i < 10; i++)
            printf("%d", b[i]);

    printf("\n%p %p\n", a, b);
}

输出是

11111
0x2558010
00111
1111100000
0x2558010 0x7f29627e6010

指针a仍然指向同一个地址,但是内容发生了变化.

Pointer a still point to the same address, but the content is changed.

推荐答案

指针a仍然指向同一个地址,但内容发生了变化.

Pointer a still point to the same address, but the content is changed.

那是因为 realloc() 可能首先尝试增加 a 指向的块的大小.但是,它可以改为分配一个新块,将数据(或尽可能多的数据)复制到新块中,然后释放旧块.你真的不应该在调用 b = realloc(a, 200000 * sizeof(int)) 之后使用 a 因为 realloc 调用可能会移动阻塞到一个新位置,让 a 指向不再分配的内存.改用 b.

That's because realloc() may first try to increase the size of the block that a points to. However, it can instead allocate a new block, copy the data (or as much of the data as will fit) to the new block, and free the old block. You really shouldn't use a after calling b = realloc(a, 200000 * sizeof(int)) since the realloc call may move the block to a new location, leaving a pointing to memory that is no longer allocated. Use b instead.

这篇关于realloc 会对旧指针做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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