Reputation: 2851
I would like to print out the contents a pointer pointing to. Here is my code:
int main(){
int* pt = NULL;
*pt = 100;
printf("%d\n",*pt);
return 0;
}
This gives me a segmentation fault. Why?
Upvotes: 5
Views: 50742
Reputation: 42083
These lines:
int* pt = NULL;
*pt = 100;
are dereferencing a NULL
pointer (i.e. you try to store value 100
into the memory at address NULL
), which results in undefined behavor. Try:
int i = 0;
int *p = &i;
*p = 100;
Upvotes: 12
Reputation: 29265
Because you are trying to write to address NULL.
Try:
int main(){
int val = 0;
int* pt = &val;
*pt = 100;
printf("%d\n",*pt);
return 0;
}
Upvotes: 5