我有两个关于动态分配数组的问题。我查了一些类似的问题,但仍然没有找到答案。
按值传递
基本上,我写了两个函数,一个用于分配,另一个用于空闲内存。当我按值传递数组指针时,分配函数不起作用(如预期的那样),但是自由函数有效。在我天真的理解中,即使我们按值传递数组指针,分配仍然可以工作,因为它在所表示的值的相同内存地址处分配内存。如果我们稍后引用该地址,无论变量名称如何,我们都应该能够找到该空间。这是代码:
void main()
{
int * array;
allocation(array);
deallocation(array);
}
void allocation(int * result)
{
result = malloc(8293 * sizeof(result));
}
void deallocation(int * result)
{
free(result);
}
对于解除分配测试,我在main函数中声明了int * array = malloc(23123 * sizeof(int)),而不是使用分配函数。再次,释放工作。
超出范围。
void main()
{
FILE * fp = fopen("sometext.txt");
int * A = malloc(100 * sizeof(int));
int * B = malloc(200 * sizeof(int));
/* Now I accidentally access A from 0-199 and B from 0-999 using a for loop*/
char buffer[500];
int i,x;
for (i=0; i<200; i++)
{
fgets(fp,buffer);
sccanf(buffer, "%d", x);
A[i]=x;
}
for (i=0; i<1000; i++)
{
fgets(fp,buffer);
sccanf(buffer, "%d", x);
B[i]=x;
}
}
两个for循环都不起作用。但是,我以某种方式通过了第一个循环并且只在第二个循环中获得了seg错误。我得到的错误可以追溯到sccanf(我测试了代码而没有为A或B分配任何值,并且它有效。所以sccanf语句应该没问题。)gdb错误消息是:isoc99_sscanf(s =,format = )。
完整的bt消息如下,SOL []是我的B [],实际的sscanf读取更多变量。如果您有兴趣,我可以发布完整的代码。
#0 0x00007ffff7a6869b in _IO_vfscanf_internal (s=s@entry=0x7fffffffd3b0,
format=format@entry=0x4010f8 "%*d%5c%5c%5d %lf %lf %lf %*f %*f %*f\n",
argptr=argptr@entry=0x7fffffffd4d8, errp=errp@entry=0x0) at vfscanf.c:343
#1 0x00007ffff7a72a0c in __GI___isoc99_vsscanf (
string=0x7fffffffd650 " 4545SOL HW123234 2.687 0.089 7.120 -1.1448 0.0920 0.6016\n", format=0x4010f8 "%*d%5c%5c%5d %lf %lf %lf %*f %*f %*f\n",
args=args@entry=0x7fffffffd4d8) at isoc99_vsscanf.c:43
#2 0x00007ffff7a72997 in __isoc99_sscanf (s=<optimized out>,
format=<optimized out>) at isoc99_sscanf.c:31
#3 0x0000000000400a9c in read (PMI=0x603490, COION=0x606ce0,
COUNTERION=0x60dd70, SOL=0x7ffff7f58010, in=0x603010, out=0x603250)
at thick_calc.c:97
#4 0x0000000000400915 in main () at thick_calc.c:52
谢谢!
答案 0 :(得分:0)
您没有重新指定指针,它应该是
void main()
{
int * array;
allocation(&array);
if (array != NULL)
deallocation(array);
}
void allocation(int **result)
{
if (result == NULL)
return;
*result = malloc(8293 * sizeof(int));
}
void deallocation(int * result)
{
free(result);
}
通过传递指针,您可以修改它的内容,但是您无法更改指向的位置,因此您必须将指针传递给指针,即指针的地址,以便您可以修改指向的位置。
您的代码中的问题是您的指针在main范围内仍然无效,因此当您将其传递给free
时,它实际上并未指向malloc
内存块。
这样做会导致未定义的行为。读取或写入malloc
ed块会导致未定义的行为,因此您不能指望给定的行为,因为它未定义。
这意味着,它可能会导致分段错误,或者它可能会起作用,或者因为未定义而发生任何事情。
最终你将写入内存中的特殊位置,会发生一些事情,你不能确定发生了什么,因为它再次是未定义的行为。