Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Step by step C compilation result in segfault

I'm trying to understand C compilation

Given this simple C code in main.c:

int main() {
    int a;
    a = 42;
    return 0;
}

I performed the following operations:

cpp main.c main.i
/usr/lib/gcc/x86_64-linux-gnu/9/cc1 main.i -o main.s
as -o main.o main.s
ld -o main.exe main.o

When executing main.exe, I get a Segmentation Fault.

How can I get a good memory addressing in this example?

like image 969
johnnnn Avatar asked Mar 03 '23 18:03

johnnnn


1 Answers

When I try the sequence of commands from your question on an x86_64 Ubuntu 19.10 system, I get a warning from ld:

ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000

This is an indication that something is wrong.

The error means that the linker did not find a symbol _start and used a default address instead. When running your program it will try to execute code at this address which apparently is invalid.

An executable program compiled from C code doesn't contain only your code. The compiler instructs the linker to add C run-time library and startup code. The startup code is responsible for initialization and for calling your main function.

Run e.g.

gcc -v -o main.exe main.o

to see what other files get added to your program. On my system this shows a few files with names starting with crt which means "C runtime".

If you don't use gcc to link your program but use ld directly, you have to manually add all necessary object files in a similar way as the compiler would do automatically.

like image 150
Bodo Avatar answered Mar 05 '23 16:03

Bodo