我正在尝试在 C 中编写一个可以获取环境变量的代码,然后使用 strstr 从该结果中搜索特定的单词。我正在使用 UBUNTU 操作系统和 gcc 编译器。这是我编写的代码。评论是我预期会发生的。
#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;
}
运行代码后,由于核心转储而崩溃。这是输出。
ABC=/tmp ,data found : ABC=/tmp
ABC=/tmp
Segmentation fault (core dumped)
据我所知,它只能执行一次 search_string 。然后它崩溃了。然后我使用 gdb 找出它实际上在哪一行崩溃,结果如下:
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.
我从调试中不明白的是,由于 SEGV 信号,它正在接收错误。有人可以指点我如何解决这个问题吗?是因为 search_string 返回 NULL 值吗?