0

I have set an environment variable with the following command:

QUERY_STRING='This is my query string'

This is my program:

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

void main (int argc, char *argv[])
{
      printf("%s\n", getenv("QUERY_STRING"));
}

And this is what I get when I run the program:

mantis@toboggan /testing/cgi_download/temp $ echo $QUERY_STRING; ./a.out
This is my query string.
Segmentation fault
mantis@toboggan /testing/cgi_download/temp $

It appears as though the environment variable is not being set, and so getenv() is returning a NULL.

I really don't know why this isn't working. Other variables like $PATH are available. How do I set this environment variable so that it's available to my program?

uname -a:

Linux toboggan 3.18.7+ #755 PREEMPT Thu Feb 12 17:14:31 GMT 2015 armv6l GNU/Linux
Deanie
  • 2,164
  • 2
  • 14
  • 30
  • Note that `main` should return `int`, not `void`. – user12205 Apr 28 '15 at 18:29
  • @ace: Not when you're reducing your code to only contain the error! But I understand where you're coming from. ;) – Deanie Apr 28 '15 at 18:32
  • False. The C standard specifies that `main` should return `int`. See http://stackoverflow.com/a/207992/3488231 – user12205 Apr 28 '15 at 18:34
  • @ace: If I change it to `int main` from `void main` then my program would require another line of code, and thus wouldn't be reduced to only show the error. – Deanie Apr 28 '15 at 19:04
  • Have you `export` ed it? For an environment variable to be available to subprocesses, you have to export it. – Luis Colorado Apr 29 '15 at 05:57

2 Answers2

3

This shell command:

QUERY_STRING='This is my query string'

creates a shell variable, not an environment variable. Shell variables are local to the shell process, not passed on to child processes like your a.out. To make it an environment variable, you need to export it:

export QUERY_STRING
  • By the way, I have not been able to reproduce your problem... When I don't export the variable it `SIGSEGV` *but no printing at all*. If I export the variable, it works fine. But I have never got both answers together. – Luis Colorado Apr 29 '15 at 05:59
1

You need to export the variable so that it propagates into the child processes:

 export QUERY_STRING='This is my query string'
eduffy
  • 35,646
  • 11
  • 90
  • 90