0

Hi there is a example in the section 7.7 of Expert C Programming which would caused segmentation fault 。

  int *p =0;
  *p =17; /*caused segmentation fault */

but i have test it as below:

#include <stdio.h>
int main()
{
        int *p =0;
        *p = 17;
        return 0;
}

when i doing gcc -c test.c it is OK and there is nothing error about segmentation fault ? why ?

march_seven
  • 691
  • 1
  • 7
  • 13

3 Answers3

0
*p=17;

p points to invaid memory and you are are storing a value there.

Its leading to undefined behaviour when you write to invalid memory, you are probably lucky program did not error in segment fault.

Pras
  • 4,047
  • 10
  • 20
  • it make me confuse that int *p = 0 is going set the pointer address as 0 not set value, and then *p=17 is going to set pointer value as 17 not set address ~~~~ although they are same format “ *pointer = value ” ; – march_seven Sep 06 '17 at 05:40
0

I add one more line in your program. It is core dumped. It will core dump, when you try to access the pointer variable, since you didn't allocate the memory for pointer variable p.

    #include <stdio.h>
    int main()
    {
            int *p =0;
            *p = 17;
            printf("%d",*p);
            return 0;
    }
Steephen
  • 14,645
  • 7
  • 40
  • 47
0

p is supposed to store the address of an integer, however, it's storing 0. Then, you are accessing address 0 and storing 17 there. 0 is likely not even a valid address so the behavior is undefined. Segfault is one of the possible outcomes.

savram
  • 500
  • 4
  • 18