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

后端 未结 4 1568
青春惊慌失措
青春惊慌失措 2021-01-21 06:12

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 

        
相关标签:
4条回答
  • 2021-01-21 06:58

    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.

    0 讨论(0)
  • 2021-01-21 07:01

    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.

    0 讨论(0)
  • 2021-01-21 07:05

    You need to initialize mem. I guess you're trying to just read random memory, but that isn't allowed. For example, you may be trying to read memory that's used by a different process, or you may be trying to read some address that doesn't even exist in your computer.

    By changing the signature for main, you've changed what random junk value is in mem to start with. The way it probably works is that mem is taking a random value from some register. When you modified the function signature, argc and argv are using those registers instead. Therefor mem is getting a different junk register value of a junk stack value. In any case, you shouldn't try to follow a junk pointer.

    Just because it works in one example, only means you got lucky. You still should not do it. It's very likely it wouldn't work if any little thing was changed.

    0 讨论(0)
  • 2021-01-21 07:09

    You never initialize mem, so its contents are undefined. When you attempt to either increment it with ++ or dereference the pointer, you get undefined behavior.

    One of the things that can happen with undefined behavior is that a program may appear to work normally, and making a seemingly unrelated change will cause a crash.

    0 讨论(0)
提交回复
热议问题