1
votes

I try to call getenv in my C code, this can return correct env string in terminal, while it returns NULL in GDB/DDD.

void main() {
  char * a = getenv("ANCHOR_STEM");
  if (strlen(a)>0)
    printf("%s\n", a);
}

The GDB/DDD is started from the same terminal. Even I "show environment", this env exists.

Anyone any idea?

OS/Tools version info: RHEL Linux hostname1 2.6.32-754.3.5.el6.x86_64 #1 SMP Thu Aug 9 11:56:22 EDT 2018 x86_64 GNU/Linux GNU gdb (GDB) 7.12 gcc (GCC) 6.3.0

3
Not related to the question but your return type of main is wrong. It must return int. And paremeter list is either (void) or (int argc, char *argv[]). Empty parameter list is obsolete. - Gerhardh

3 Answers

1
votes

include proper header files

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

Treat warning as error.

1
votes

Even I "show environment", this env exists.

When GDB invokes your program, it starts a new shell to run this program in.

When the environment changes for the target program, most often this is the result of your shell initialization file (~/.bashrc, ~/.kshrc, etc.) changing the environment.

It is a really bad idea to change environment for non-interactive shells. Documentation on how to avoid it.

0
votes

If getenv returns NULL it is because it does not find the environment variable. but still you have to be careful. This instruction if (strlen(a)>0) becomes illegal, if getenv(....), fails. getenv sends back NULL and this instruction crash the program. It's better to test the validity of the pointer before to execute this line if (strlen(a)>0) -> which is not necessarily useful.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char * a = getenv("ANCHOR_STEM");
    if( NULL != a ){
        (void)puts(a);
        return EXIT_SUCCESS;
    }
    (void)puts("none");
    return EXIT_FAILURE;
}