vaibhav agnihotri
vaibhav agnihotri

Reputation: 15

Why is the following code producing segmentation fault?

#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;
}

The program is compiling successfully without any errors.On running the program and after entering the first value in the array the program terminates with the segmentation fault.I'm using gcc compiler on ubuntu 12.04 running on vmware.

Upvotes: 0

Views: 46

Answers (1)

Eugene Sh.
Eugene Sh.

Reputation: 18299

if(ptr=NULL) should be if(ptr == NULL). Otherwise you are setting ptr to NULL and trying to access it. Generally a compiler should warn about it. Some programmers are using the following method to avoid this type of bugs: if(NULL == ptr). In this case, if you forget one = you will get a compilation error.

Upvotes: 6

Related Questions