【问题标题】:Segmentation fault (core dumped) error with strcpy() (suspected)strcpy() 的分段错误(核心转储)错误(怀疑)
【发布时间】:2013-09-04 11:09:46
【问题描述】:

我在这段简短的代码中尝试解决运行时分段错误时遇到了麻烦。我怀疑这与在代码中使用 system() 和 strcpy() 有关,但由于我没有遇到过这种类型的错误,我不确定该怎么做,到目前为止我还没有找到很多有用的页面。

代码:

#include <stdio.h>
#include <string.h>
int main(){
        char command[31], string[128];
        strcpy(string, (char *)system("grep -Po '(?<=testString\\s)\\S+' File"));
        string[strlen(string)] = '\0';
        printf("%s", string);
        return 0;
}

我正在使用 GCC 4.7.3 来编译程序。非常感谢您对此提供的任何帮助。

【问题讨论】:

  • 您正在将 int 的返回值 system 转换为一个字符串......这没有什么好处。
  • 你对system的使用是错误的,你可能要使用popen(3)
  • 使用系统或其他 API cal 时,您应该阅读有关该调用的文档以确定它接受和返回什么。 system 不返回您正在执行的命令的输出。它只提供一个返回码。如果要捕获输出,可以将system 调用输出到调用后打开和读取的文件,或使用管道(popen 等)。
  • 除了system 错误之外,string[strlen(string)] = '\0'; 行完全是愚蠢的!如果字符串末尾不包含 0,strlen 将搜索甚至超过缓冲区的一个,然后您将在已经存在的 0 上写入一个 0。该语句非常浪费,充其量没有,最坏的情况是分段错误。
  • 感谢您的反馈@tristopia,我将删除该行。

标签: c segmentation-fault strcpy


【解决方案1】:

system 不返回char *,而是返回int。使用它的返回值作为字符串 - char * - 很可能会给你段错误。

int system(const char *command);

返回值 错误时返回的值为 -1(例如 fork(2) 失败),并且 否则返回命令的状态。后一种返回状态是 以 wait(2) 中指定的格式。因此,命令的退出代码 将是 WEXITSTATUS(status)。如果 /bin/sh 无法执行, 退出状态将是执行 exit(127) 的命令的状态。

【讨论】:

  • 感谢您的快速回复!谢谢@mbratch,我一定会调查的:)
【解决方案2】:

system 命令出错时返回 -1,否则返回命令状态。

在这种情况下,类型转换 integer return value 会导致 segmentation fault。

要将命令的输出复制到缓冲区中,我们可以使用popen,它返回一个文件指针FILE *,您可以从中读取命令输出。

代码如下:

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


int main( int argc, char *argv[] )
{

  FILE *fp;
  char string[128];


  /* Open the command for reading. */
  fp = popen("grep -Po '(?<=testString\\s)\\S+' File ", "r");

  if (fp == NULL) {
        printf("Failed to run command\n" );
        exit;
  }

  /* Read the output of command */
  while (fgets(string, sizeof(string)-1, fp) != NULL) {
        printf("%s", string);
  }

  /* Close */
  pclose(fp);

  return 0;
}

【讨论】:

    猜你喜欢
    • 2015-08-10
    • 1970-01-01
    • 2014-08-04
    • 2012-11-19
    • 1970-01-01
    • 2015-06-25
    • 2021-06-03
    相关资源
    最近更新 更多