0

If getenv is supposed to return a pointer to the value in the environment shouldn't this program work for printing out the string value of the environment variable?

#include <stdio.h>
#include <unistd.h>

int main() {

   printf("HOME=%s\n",getenv("HOME"));

   return 0;
}

I am getting the following warning when I compile:

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’

And when I run the program I get a Segmentation Fault.

I am using Ubuntu and I am wondering if this has to do with permissions or another form of security.

Kyle Bridenstine
  • 6,055
  • 11
  • 62
  • 100

1 Answers1

2

You need #include <stdlib.h> since that's where getenv() is declared.

Also, consider using the -Wall option to enable more diagnostics from gcc or MSVC (or most compilers). In this case, gcc would have said:

warning: implicit declaration of function 'getenv' [-Wimplicit-function-declaration]

and MSVC would have said:

warning C4013: 'getenv' undefined; assuming extern returning int
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • Right. Compiler needs to know the prototype of function before the function call is made otherwise compiler assumes the default function prototype i.e. int function(int, int). That is probably why topic poster is encountering that warning. – awatan Oct 18 '14 at 21:46
  • Thanks for the -Wall tip I tried that when I compiled and I got the output warning you showed. That helps tremendously. – Kyle Bridenstine Oct 18 '14 at 21:52
  • 1
    @Bridenstine: see http://stackoverflow.com/questions/10201192, but be sure to read Jonathan Leffler's warning. Also see http://www.mingw.org/wiki/HOWTO_Use_the_GCC_specs_file for more info about the specs file. I think if a makefile is running the build, just add the options to the `CFLAGS` variable (or similar for whatever build tool you're using). If you're running the compiler by hand on the command line, I think most people do this kind of thing using a script or alias to run the compiler. Something like: https://gcc.gnu.org/ml/gcc/2001-01/msg00297.html – Michael Burr Oct 18 '14 at 22:07