Why this version of C code is not working (cause segmentation fault)
#include <stdio.h>
int main()
{
int *p;
*p = 10;
return 0;
}
while this one is working?
int main()
{
char c = 'c';
int *p;
*p = 10;
return 0;
}
Why this version of C code is not working (cause segmentation fault)
#include <stdio.h>
int main()
{
int *p;
*p = 10;
return 0;
}
while this one is working?
int main()
{
char c = 'c';
int *p;
*p = 10;
return 0;
}
For int* p
, no storage space is allocated for the actual integer number.
You need to modify your code as follows to make it work properly.
In C++, you can use new
, but in C you can use malloc
.
#include <stdio.h>
int main()
{
int* p = malloc(sizeof(int));
*p = 10;
free(p);
return 0;
}
Both code snippets are wrong, we can't say that one is more wrong than the other, p
is uninitialized in both cases and therefore it may or may not contain a valid memory address, it's impossible to predict, this means that the behavior is undefined. That being the case, working, whatever that may mean, is well within the realm of possible outcomes.