4

I have to do my homework but I can not take path in C.For example ;

int main(void) {
  char *path;
  path = getenv("PATH");
  if(path)
    printf("The current path is: %s\n", path);
  return 0;
}

If I run this code , I got "Segmentation fault (core dumped)". My os is Ubuntu 14.04 LTS.

SemihY
  • 249
  • 1
  • 4
  • 14

1 Answers1

8

Add

#include <stdlib.h>

to the top of the listing and give that a try. It might be an assumed int return for getenv to char * pointer tripping up the code.

Brian Tiffin
  • 3,978
  • 1
  • 24
  • 34
  • If that's the problem, then `stdio.h` needs to be `#include`d as well for `printf`. – 5gon12eder Dec 07 '14 at 21:38
  • I tried this myself and indeed it works after adding that line. – Crembo Dec 07 '14 at 21:38
  • 1
    It has to do with sign extending 64bit values. Using %p in a printf, you'd see `'pointer variable: 0xffffffffa30d6982' Segmentation fault (core dumped)` An address of 0x7fffffffx30d6982 as improperly cast due to the return assumption. That is to properly declare getenv. Including stdio.h wouldn't really help with the miscast from getenv, but it is smart and proper, regardless. – Brian Tiffin Dec 07 '14 at 21:49