Thursday, October 08, 2009

Why `Segmentation fault' occurs in C

これだと
#include <stdio.h>

int main()
{
int thing = 2;
printf("Thing %d\n", thing);
int *thing_ptr;
*thing_ptr = 3;
printf("Thing %d\n", *thing_ptr);
return (0);
}


正常で
% gcc -g -Wall -o example01 ./example01.c 
% ./example01
Thing 2
Thing 3
%


なぜ、これだと
#include <stdio.h>

int main()
{
//int thing = 2;
//printf("Thing %d\n", thing);
int *thing_ptr;
*thing_ptr = 3;
printf("Thing %d\n", *thing_ptr);
return (0);
}


こうなる?
% gcc -g -Wall -o example01 ./example01.c 
% ./example01
Segmentation fault
%

No comments: