返回指针时出现分段错误

时间:2013-10-29 02:55:56

标签: c segmentation-fault signals coredump strstr

我正在尝试在C中创建一个可以获取环境变量的代码,然后使用strstr从该结果中搜索特定的单词。我正在使用UBUNTU OS和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值吗?

2 个答案:

答案 0 :(得分:2)

问题是,如果search_string()找不到字符串,则会返回NULL。然后,您将NULL传递给崩溃的printf()

main()中,您需要以下内容:

if (tmp2)
    printf("%s\n", tmp2);

此外,tmp2变量的类型应为char *,而不是char **。并且没有理由不将其声明为main()

答案 1 :(得分:0)

对主循环的一个非常简单的更改会阻止程序崩溃:

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
// >>>>> change these next two lines:
      if(tmp2 != NULL) printf("%s\n",tmp2);             //print the return value
      else printf("%s does not contain ABC\n", environ[x]);
// <<<<< end of change
      }  //If the search_string return NULL, does it consider string or something else?
      return 0;
}

请注意,如果您只期望一场比赛,则可以在打印比赛时添加break;。上面的代码打印出所有环境变量 - 你可以看到它不会停止......