I am working on a simple program for learning purposes and I see the following behavior:
If I attempt to read an environment variable using getenv it works as expected:
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("PATH is %s", getenv("PATH"));
return 0;
}
If I do not include stdlib.h, I get the expected warning:
env.c:7:26: warning: implicit declaration of function ‘getenv’; did you mean ‘getline’? [-Wimplicit-function-declaration]
The program still compiles. Running the program with the header runs as expected, the program without the header included gets a seg fault.
If I inspect the disassembly of both programs, I see that there is a call to getenv@PLT
call getenv@PLT
When I output the disassembly of the 2 programs (where the only difference in the c source code is the header include), the only difference I see is that when we include the header there's an instruction to set %eax to 0 before calling getenv.
movl $0, %eax
If I step through in gdb for the program without included header, it does jump into getenv and does run a whole lot of code within the c runtime.
I am wondering what is the exact reason why not including the header here causes this kind of behavior? Why does c let this compile?
Some info: gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1) I am compiling like this: gcc -O0 -S env.c