#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int *ptr;
int max;
int i=0,number=0;
printf("Enter the size of array \n");
if( scanf("%i",&max) != 1)
{
printf("number not enterd correctly\n");
exit(EXIT_FAILURE);
}
ptr=(int *)malloc(max * sizeof(int));
if(ptr=NULL)
{
puts("Error in recieving memory");
exit(EXIT_FAILURE);
}
else
{
puts("Enter array");
while(i<max && scanf("%d",&ptr[i]) == 1)
++i;
/* number=i;
puts("Array entered is ");
for(i=0;i<number;i++)
printf("%i %i\n",i,ptr[i]);
*/
}
puts("Done!");
free(ptr);
return 0;
}
程序编译成功,没有任何错误。在运行程序时,在数组中输入第一个值后,程序因段错误而终止。我在 vmware 上运行的 ubuntu 12.04 上使用 gcc 编译器。
最佳答案
if(ptr=NULL)
应该是 if(ptr == NULL)
。否则,您会将 ptr
设置为 NULL
并尝试访问它。通常,编译器应该对此发出警告。一些程序员正在使用以下方法来避免此类错误:
if(NULL == ptr)
。在这种情况下,如果您忘记了一个 =
,您将得到一个编译错误。
关于c - 为什么以下代码会产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29523765/