I'm trying to make a code in C that can get environment variable and then search for a specific word from that result using strstr. I'm using UBUNTU OS and gcc compiler. Here is the code that I've written. The comment are what I expected to happen.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
extern char **tmp;
extern char **tmp2;
char *search_string(char *tmp,int x)
{
char string[]="ABC"; //I'm looking for ABC in the environment variable
char *pointer;
pointer=strstr(tmp,string); //pointer will point to the result of strstr
if(pointer != NULL)
{ printf("%s ,",tmp);
printf("data found : %s \n",pointer);
} else {
//hope to do something
}
return (pointer);
}
int main(char *tmp2)
{
int x = 0;
for(x=0;environ[x]!='\0';x++){ //I'm expecting it to keep looping until finish
tmp2=search_string(environ[x],x); //tmp2 will point to the function return value
printf("%s\n",tmp2); //print the return value
} //If the search_string return NULL, does it consider string or something else?
return 0;
}
After running the code, it crashes because of core dump. Here are the output.
ABC=/tmp ,data found : ABC=/tmp
ABC=/tmp
Segmentation fault (core dumped)
From what I see, it can only do the search_string for only 1 time. Then it crashes. Then I use gdb to find out at what line does it actually crash and here are the result:
Starting program: /home/fikrie/a.out
ABC=/tmp ,data found : ABC=/tmp
ABC=/tmp
Program received signal SIGSEGV, Segmentation fault.
__strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99 ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
What I dont understand from the debug is that it's receiving error because of SEGV signal. Can someone point me on how to solve this problem? Is it because the search_string returns a NULL value?