Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting segfault when changing the signature of main?

I am trying to get my feet into C, and wrote this program that displays a kb of my RAM in a random location. Here is the code, and it works fine:

#include <stdio.h>

int main(){
    char *mem;
    for(int i =0; i < 1024; i++){
        mem++;
        printf("%c", *mem);
    }
    return 0;
}

After that, I did the following change in my code, and I get segfaults every time I run my program:

#include <stdio.h>


// Just added this signature
int main(int argc, char *argv[]){
    char *mem;
    for(int i =0; i < 1024; i++){
        mem++;
        printf("%c", *mem);
    }
    return 0;
}

My spider senses tell me that the segfaults I get are random, and should also be caused in the first example, but running the different programs again and again makes it look like predictable behaviour.

$ gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
like image 494
Loupax Avatar asked Dec 30 '25 21:12

Loupax


2 Answers

Both your snippets invoke undefined behavior as you try to

  1. Go out of bound (mem++;, with no allocation)
  2. use uninitialized values (accessing *mem )

with the current version.

Remember, pointers do not magically inherit (or acquire) memory, you need to make a pointer point to something valid, in general.

like image 150
Sourav Ghosh Avatar answered Jan 02 '26 14:01

Sourav Ghosh


The value of mem is undefined (not initialized), but not random. If before main is called, other C runtime functions, are called, then the slot of stack used by mem may have a valid pointer within it. Adding parameters to main changes which slot is used and changes behaviour. This can mean the code doesn't crash, although it is not correct.

like image 22
mksteve Avatar answered Jan 02 '26 12:01

mksteve