Segmentation Fault ? C

186 Views Asked by At

I don't understand why this code provoke no Segmentation Fault :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void){
    char* c;
    strncpy(c,"Gustave",10);
    return 0;
}

And this one does :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void aux (void){
    char* c;
    strncpy(c,"Gustave",10);
}

int main (void){
    aux();
    return 0;
}

For me the two are supposed to make a Segmentation Fault because we are accessing non allocated memory.

Another question would be :

Why does this provoke a Bus Error, not a segmentation Fault :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void aux (void){
   char* const c = "Bonjour";
   strncpy(c,"BonjourBonjour",20);
}

int main (void){
    aux();
    return 0;
}
3

There are 3 best solutions below

0
On

If the code 1 don't segfault, it's because you have "luck" : the string may be written in memory allocated to your program and not in the second code.

0
On

It will generate undefined behavior since as you correctly pointed you're trying to copy into unallocated memory but in my IDE it's generating a seg fault for both cases. Just to add to the edit bus errors occurs when your processor cannot even attempt the memory access requested. Segmentation faults occur when accessing memory which does not belong to your process

0
On

There is nothing to understand. All your snippets have undefined behavior, and that's the end of that as far as the language is concerned.

The compiler and runtime have no obligation to do anything specific with what you wrote. The compiler could refuse to compile entirely, or compile a completely different program instead. You are not guaranteed a seg fault, bus error or any other OS-specific behavior.

Depending on luck, what random garbage was in your un-initialized variables, how the stack was laid out at that point, etc., the code might even do what you want and the error could stay undetected for ages leading to one of the worst kinds of bugs to hunt down.

Write proper code, turn on all warnings, compile with different compilers and optimization settings, and use tools like valgrind to try and make sure your code is clean.