0

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

anbocode
  • 53
  • 6
  • Does this answer your question? [Printing null pointer gives ""Segmentation fault (core dumped)](https://stackoverflow.com/questions/26362340/printing-null-pointer-gives-segmentation-fault-core-dumped) – Raymond Chen Jun 26 '22 at 17:27
  • 1
    The first two examples are correct, the last two exercise undefined behavior (dereferencing a `NULL` pointer). What did you _expect_? – Employed Russian Jun 26 '22 at 17:28

1 Answers1

0

The problem is, that the pointer points to an invalid address (NULL). By calling 'calloc' you are allocating memory and store that address in the passed pointer (meaning the value you pass into the function is completely irrelevant).

Accessing an invalid address leads to undefined behavior. Dereferencing NULL causes a segmentation fault.

A real world example should illustrate that better:

Imagine you walk down a path. You come to a crossing with a waypost. Usually, it would point you 'into the right direction'. But now it just points to nowhere. Following it will land you in hot water, a swamp, a big black hole or any other unpleasant place of your choosing.

Refugnic Eternium
  • 4,089
  • 1
  • 15
  • 24