ANSI C结构{与动态数组}分配到阵列中,realloc的 [英] ansi c struct {with dynamic array} assigned to array which is realloc
问题描述
为什么低于code给我的错误双重释放或腐败......当我编译,并与海湾合作委员会执行[(Debian的4.4.4-8)4.4.5 20100728($ P $租赁前) 。在此先感谢!
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;typedef结构
{
INT *索引1;
}数据;无效斗为(int *);INT主(INT ARGC,CHAR *的argv [])
{
为int * A =(INT *)malloc的(10 * sizeof的(INT));
INT I; 对于(I = 0; I&小于10;我+ +)
{
一个由[i] = 2 * I;
} 斗(一); 数据之一;
one.index1 =一个; 的printf(%d个\\ N,one.index1 [4]); 自由(一); 的printf(%d个\\ N,one.index1 [4]); 免费(one.index1);
返回0;
}无效斗(INT * B)
{
B =(INT *)realloc的(B,5 *的sizeof(INT));
返回;
}
one.index1 =一个;
...
自由(一);
...
免费(one.index1);
...
因此,这个双重释放。
无效斗(INT * B)
{
B =(INT *)realloc的(B,5 *的sizeof(INT));
返回;
}
当你传递一个指针给这个函数,它的值(这是逸岸一个地址),被复制到B,另一个本地INT指针。
现在,当你5整数realloc的空间,它改变了逸岸的空间分配。所以,你的空间会从10至5整数降低。
由于所要求的OP,要获得相同的数据和放大器;单独的内存指针,空间必须重新分配为新指针的指针是毕竟只是一个变量,拿着一个地址。如果您分配两个独立的模块,你会得到两个不同的地址,可单独释放。
why the below code gives me error of "double free or corruption"... when i compile and run with gcc [(Debian 4.4.4-8) 4.4.5 20100728 (prerelease)]. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int *index1;
} data;
void doo(int *);
int main(int argc, char *argv[])
{
int *a = (int *) malloc(10*sizeof(int));
int i;
for(i=0; i<10; i++)
{
a[i] = 2*i;
}
doo(a);
data one;
one.index1 = a;
printf("%d\n", one.index1[4]);
free(a);
printf("%d\n", one.index1[4]);
free(one.index1);
return 0;
}
void doo(int *b)
{
b = (int *) realloc(b, 5*sizeof(int));
return;
}
one.index1=a;
...
free(a);
...
free(one.index1);
...
Ergo, the double free.
void doo(int *b)
{
b = (int *) realloc(b, 5*sizeof(int));
return;
}
When you pass the a pointer to this function, its value(which is infact an address), gets copied into b, another local int pointer. Now, when you realloc space for 5 ints, it changes the space allocation for a infact. So your space gets reduced from 10 to 5 ints.
As requested by OP, to get the same data & separate memory pointers, space must be allocated afresh for the new pointer, as a pointer is after all, just a variable, holding an address. If you allocate two separate blocks, you would get two separate addresses, which can be freed individually.
这篇关于ANSI C结构{与动态数组}分配到阵列中,realloc的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!