C具有不同指针的相同地址?

标签 c arrays pointers int dereference

int *ptr = calloc(10,(sizeof(int)));
int *ptr2 = (ptr);
for (int i = 0; i < 10; ++i) {
    int r = rand() % 20000;
    *(ptr + i) = r;
    printf("[i:%d, v:%d, a:%p]", i, *(ptr + i), ptr+i);
    fflush(stdout);
}
printf("\n");
printf("[v:%d, a:%p]", *(ptr2), ptr2);
printf("\n");

*ptr2=5;
printf("[v:%d, a:%p]", *(ptr2), ptr2);
printf("\n");
for (int i = 0; i < 10; ++i) {
    printf("[i:%d, v:%d, a:%p]", i, *(ptr + i), ptr+i);
}
printf("\n");

free(ptr2);
free(ptr);

这是输出:

[i:0, v:5933, a:0x600010360][i:1, ...

[v:5933, a:0x600010360]
[v:5, a:0x600010360]

[i:0, v:5, a:0x600010360][i:1, ...

请解释为什么同一个地址有两个不同的值? - 这实际上并没有发生..

而且按照我的方式释放指针也会出错:

* 检测到 glibc */home/travis/build/batousik/Practical-C2/bin/.libs/lt-practical_trees: double free or corruption (fasttop): 0x0000000000e05010 ***

在实际程序中,我有 int 数组和 Tree 数据类型的测试数据。我用数组中的一些数据填充树,然后我试图以递归方式释放树中节点和节点的每个值,但失败了。是因为节点中所有的值指针其实都是一个内存块吗?然后我应该做一些事情,比如将数组中的值 memcopy 到新分配的节点值内存空间中吗?

最佳答案

  1. 因为您两次释放同一个指针。您在下一行中指向 calloc()1 返回的地址

    ptr = calloc(10, sizeof(int));
    

    然后你让ptr2指向同一个地方

    ptr2 = ptr;
    

    所以释放 ptrptr2 实际上释放的是同一个指针。

  2. 没有任何迹象表明给定地址的值实际上有两个值,只是

    *ptr2 = 5;
    

    更改 ptrptr2 指向的第一个元素的值,实际上您总是在打印前覆盖该地址处的值。

如果您在代码中调用有问题的 free() 之前执行此操作

fprintf(stderr, "value of ptr : %p\n", ptr);
fprintf(stderr, "value of ptr2: %p\n", ptr2);

将打印相同的值,因此您实际上需要一次调用 free() 传递任何 ptr ptr2 一个pass后另一个不传


1如果要在 calloc()< 之后显式初始化数据,则无需使用 calloc()/ 调用。此外,您应该检查 calloc()/malloc() 是否返回 NULL

关于C具有不同指针的相同地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920445/

相关文章:

c - 解析符号链接(symbolic link)同时避免超时

c++ - 如何报告异或为零的子数组的索引?

c++ - 递归可迭代模板函数 C++

c# - 在字节数组中设置特定位

相同地址的C结构分配有效吗?

c - C 中 char *str ="this is a string"与 char *str = strdup ("this is a string"之间的区别是什么

光标不动

c - C 中的二维数组,地址生成

在 Segmentation Violation 后恢复生机

c - 使用具有边界条件的指针扫描二维数组