Trying to understand what exactly happens in the memory during the execution of this code and why it causes a segmentation error.
#include <stdio.h>
int main() {
int* ptr;
*ptr = 5;
printf("%d", *ptr);
return 0;
}
Trying to understand what exactly happens in the memory during the execution of this code and why it causes a segmentation error.
#include <stdio.h>
int main() {
int* ptr;
*ptr = 5;
printf("%d", *ptr);
return 0;
}
All variables must first be initialized to a valid value before you can use them in an expression like *p
. For pointers, this means assigning an address to point to. You can do this either by taking the address of another variable or by dynamically allocating memory with malloc()
.
When you try to dereference an uninitialized pointer with *p
, it will use whatever memory address happens to be stored in p
at that time. Most likely this address is invalid for you to use and so you get a segfault.
First allocate memory to the pointer variable
ptr = (int* ) malloc(sizeof(int))