【问题标题】:Why is the following code producing segmentation fault?为什么以下代码会产生分段错误?
【发布时间】:2015-04-08 19:33:01
【问题描述】:
#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 编译器。

【问题讨论】:

    标签: c segmentation-fault malloc


    【解决方案1】:

    if(ptr=NULL) 应该是 if(ptr == NULL)。否则,您将 ptr 设置为 NULL 并尝试访问它。通常编译器应该警告它。一些程序员正在使用以下方法来避免此类错误: if(NULL == ptr)。在这种情况下,如果你忘记了一个=,你会得到一个编译错误。

    【讨论】:

    • 作为副作用free(ptr); 不会释放内存,因为您丢失了它的指针。
    • 在这种情况下什么会释放(ptr);因为它现在指向 null??
    • 该标准保证 free 使用 NULL 指针什么都不做。
    • @mch 所以我修改了我的评论。
    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多