Mithun B
Mithun B

Reputation: 284

C program pointer not holding valid address still not giving segmentation fault

The segmentation fault error in C programs occurs because we try to access address not allocated to current program's resource.

I was trying to get a segmentation fault error with the below code. And I am not able to understand why in main function the last call for function check() do not give segmentation fault.

#include <stdio.h>

int check(char * memptr);
int foo(char * memptr);

int main()
{
    char mem = 'a';
    char * memptr = NULL;
    char * cantcatch;
    check(&mem);                        // valid pointer
    check(memptr);                      // error case, but can be checked
    check(cantcatch);                   // error case, but can't catch
    return 0;
}

int check(char * memptr)
{
    if (NULL == memptr)
    {
        printf("\n  error, function foo() not called \n");
        return 1;
    }
    else
    {
        printf("\n After = %c, ret val = %d, Before = %c, Before = %d \n", \
        *memptr, foo(memptr), *memptr, *memptr);
    }
    return 0;
}

int foo(char * memptr)
{
    *memptr = 'b';
    return 0;
}

If I try to print the 'memptr' pointer then it gives this segmentation fault error.

Any hint in understanding this will be greatly helpful.

Upvotes: 0

Views: 109

Answers (1)

Tomer
Tomer

Reputation: 1646

It depends on the value of "cantcatch" - which is undefined (random value). If the value is out of the memory scope of your program - then the program will segfault.

If it's within the scope of your program then the program will not crash but potentially cause corruption to memory.

These invalid read/writes can easily be caught by memory profiling tools such as "Valgrind".

Upvotes: 3

Related Questions