0
#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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

As a side-effect free(ptr); won't release the memory, since you lost its pointer.
In this case what will free(ptr); since it is now pointing to null??
the standard guarantees that freeing a NULL pointer does nothing.
@mch So I amend my comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.