I’m very new to C, but have no idea why this program breaks. The program compiles and runs if I remove the lines that have to do with i, but if I assign i, I can no longer assign anything to *ptr without the program breaking.
int main(void)
{
int i;
int *ptr;
i = 2;
*ptr = 5;
printf("%d",*ptr);
}
You leave the pointer with uninitialized value. So when you dereference it (
*ptr), you access arbitrary place in memory, resulting in a segmentation fault.Point
ptrat something by assigning toptritself (not*ptr) an address of a variable (like&i) or some freshly allocated memory (likemalloc(sizeof(int))).