The follwing code is self explanatory. The pointer p is sent to function f() from the main function. Inside the f1() function the values is changed to 'a' and the same gets reflected in function main().
void f(char *p)
{
*p = 'a';
}
int main()
{
char v;
char *p = &v;
f(p);
printf("%c", *p);
// Output : a
return 0;
}
The following code works too...
char *f(char *p)
{
p = (char*)calloc(1, sizeof(char));
*p = 'a';
return p;
}
int main()
{
char *p = NULL;
p = f(p);
printf("%c", *p);
// Output : a
return 0;
}
But in the follwing two code samples, I have tried to achieve the same with NULL pointer, but instead of expected result 'a', I am getting segmentation fault.
Code no. 1
void f(char *p)
{
*p = 'a';
}
int main()
{
char *p = NULL;
f(p);
printf("%c", *p);
// Output : Segmentation fault (core dumped)
return 0;
}
Code no. 2
char *f(char *p)
{
*p = 'a';
return p;
}
int main()
{
char *p = NULL;
p = f(p);
printf("%c", *p);
// Output : Segmentation fault (core dumped)
return 0;
}
Please kindly help me to understand the above codes where I am getting "Segmentation fault."
Thanks