The following C code returns a \"segmentation fault\" error. I do not understand why it does not return the value 20. What is my error?
#include
You haven't allocated space for your int
, you've only declared a pointer to an int
.
The pointer is uninitialized, and so writing to that unknown space in memory is undefined behavior and causes problems. This typically causes a segfault.
You can allocate a slot for an integer using malloc
:
n = malloc(sizeof(int));
And use a corresponding call to free
to free up the memory later:
free(n);
But allocating a single slot for an integer is pretty unusual, typically you would allocate the int
on the stack:
int n;
n = 20;