gpt4 book ai didi

c - 为什么 free(pointer) 会出现运行时错误?

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:37 25 4
gpt4 key购买 nike

我有以下 C 程序。它要求用户提供坐标数。然后使用 malloc 分配内存,将坐标(整数)存储在分配的内存中,然后释放内存。

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]) /* Arguments to main() not necessary but used to keep with convention.*/
{
int num_of_coordinates;
printf("How many co-ordinates: ");
scanf("%d", &num_of_coordinates);

int *coordinate_array = malloc(num_of_coordinates * 2);
int i, j;

/* Below for loop takes the x and y coordinate of all points. */
/* These coordinates are stored in coordinate_aaray[]. */
for (i=0; i < num_of_coordinates*2; i++)
{
j = (i / 2) + 1 ;
if (i % 2 != 0)
{
printf("Enter x coordinate of point %d: ",j);
scanf("%d",&coordinate_array[i]);
}
else
{
printf("Enter y-coordinate of point %d: ",j);
scanf("%d",&coordinate_array[i]);
}
}

for (i=0; i < num_of_coordinates*2; i++)
{
printf("%d ",coordinate_array[i]);
}
printf("\n");

/* Free the allocated memory. */
free (coordinate_array);

return 0;
}

当我运行这些程序时,在 number_of_coordinates 等于或小于 3 之前,我没有遇到任何问题。

-bash-4.1$ ./a.out
How many co-ordinates: 3
Enter y-coordinate of point 1: 1
Enter x coordinate of point 1: 2
Enter y-coordinate of point 2: 3
Enter x coordinate of point 2: 4
Enter y-coordinate of point 3: 5
Enter x coordinate of point 3: 6
1 2 3 4 5 6
-bash-4.1$

但是,当我将 num_of_coordinates 的值设置为 4 或更大时,我会遇到运行时错误(很可能是因为 free(coordinate_array))。

-bash-4.1$ ./a.out
How many co-ordinates: 4
Enter y-coordinate of point 1: 1
Enter x coordinate of point 1: 2
Enter y-coordinate of point 2: 3
Enter x coordinate of point 2: 4
Enter y-coordinate of point 3: 5
Enter x coordinate of point 3: 6
Enter y-coordinate of point 4: 7
Enter x coordinate of point 4: 8
1 2 3 4 5 6 7 8
*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x000000000185b010 ***

实际上运行时错误消息很长,所以我只显示了该错误的第一行。

为什么在这种情况下 num_of_coordinates 大于或等于 4 时会发生此错误?

谢谢。

最佳答案

这条线有很多问题:

int *coordinate_array = malloc(num_of_coordinates * 2);

1) the amount of allocated memory is 1byte * num_of_coordinates * 2
That is not large enough to hold num_of_coordinates*2 integers
use:

int *coordinate_array = malloc(num_of_coordinates * 2 * sizeof int);

2) always check the returned value from malloc (and family)
to assure the operation was successful

int *coordinate_array = NULL;

if( NULL == (coordinate_array = malloc(num_of_coordinates * 2 * sizeof int) ) )
{ // then, malloc failed
perror( "malloc for coordinate array failed" );
exit( EXIT_FAILURE );
}

// implied else, malloc successful

关于c - 为什么 free(pointer) 会出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28619213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com