【问题标题】:Segmentation fault in shell programshell程序中的分段错误
【发布时间】:2012-10-03 12:51:28
【问题描述】:

我一直在尝试创建自己的 shell 程序,并且我一直在查看的教程建议使用 strtok() 函数。虽然,我无法简单地解析我的命令行并且我不确定我做错了什么。在 parseCmd() 函数中第一次使用 strtok() 时,我不断收到 Segmentation Fault

到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#define MAXSIZE 512

int parseCmd(char *cmd, char *args[])
{
    printf("LOGGER: parseCmd(cmd=%s, args=%p)\n", cmd, args);

    char cmdDelims[] = " >";

    char *cmdReader;
    cmdReader = strtok(cmd, cmdDelims);

    printf("LOGGER: cmdReader=%s\n", cmdReader);

    int i = 0;
    while (cmd != NULL)
    {
        printf("LOGGER: %d counter", i);

        args[i] = strdup(cmdReader);
        cmdReader = strtok(NULL, " >");
        i++;
    }
}

int main() 
{   
    char *in;
    in = malloc(MAXSIZE);

    char *args[10];
    char *cmd = NULL;

    int errorBit = 0;
    int terminationBit = 1;

    char inDelims[] = "\n";

    while (terminationBit)
    {
        printf("mysh>");
        fgets(in, MAXSIZE, stdin);

        cmd = strtok(in, inDelims);

        errorBit = parseCmd(cmd, args);
        if (errorBit)
        {
            fprintf(stderr, "Error: Cannot parse command %s\n", cmd);
            exit(1);
        }

        if (*args == "exit")
        {
            terminationBit = 0;
        }
    }
    return 0;
}

我们将不胜感激有关此主题的任何帮助或建议。

编辑: 根据输出,segfault actual 可能不是 strtok()

这是一些输出:

mysh>hi sup
LOGGER: parseCmd(cmd=hi sup, args=0x7fff50ec0b80)
LOGGER: cmdReader=hi
Segmentation fault: 11

【问题讨论】:

  • 使用 valgrind。它将为您提供所需的内存错误和泄漏信息。有关更多调试信息,如函数和问题所在行,请在运行 valgrind 之前使用 -g 编译您的程序。
  • 我是用-g编译后正常运行程序还是有特殊的方法通过valgrind运行程序?

标签: c shell segmentation-fault


【解决方案1】:

似乎是一个简单的错误:

while (cmd != NULL)
{
    // ...
}

...应该是:

while (cmdReader != NULL)
{
    // ...
}

...因为cmd 很可能永远不会变成NULL。另外,这个:

if (*args == "exit")
{
    terminationBit = 0;
}

...可能不会按照你的想法去做。要比较字符串,请使用:

if (strcmp(*args, "exit") == 0)
{
    terminationBit = 0;
}

您必须确保 parseCmd 也返回一些内容,否则在此:

errorBit = parseCmd(cmd, args);

...parseCmd 产生未定义的行为,因此 errorBit 的值也完全未定义,您随后检查其值的条件也是如此。

最后,你的程序会泄漏内存,因为你 strdupmalloc 并且永远不会空闲。完成args 后不要忘记free

【讨论】:

  • 甚至没有测试它,这正是我的问题所在。谢谢
猜你喜欢
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2018-04-25
  • 2012-10-12
  • 2018-03-21
  • 2018-11-18
  • 2011-05-23
相关资源
最近更新 更多