简单命令行程序中的分段错误

时间:2014-02-28 13:37:01

标签: c++ c segmentation-fault

我正在尝试创建一个简单的程序,该程序在作为命令参数输入的文件位置上使用system()调用cat。但是每次调用文件时我都会遇到分段错误(核心转储)。你能否检查一下为什么(我在程序中的任何地方都看不到我正在做内存以获得此错误!)。

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

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("usage: %s filename", argv[0]);
    }
    else
    {
        printf("commad: %s", strcat("cat ", argv[1]));
        system(strcat("cat ", argv[1]));
    }
    return 0;
}

3 个答案:

答案 0 :(得分:3)

您无法修改字符串文字,例如"cat "它们通常在加载可执行文件时存储在内存中的只读段中,当您尝试修改它时,您将收到您提出的分段错误解释一下。

考虑使用std::string代替,它是更惯用的C ++方式:

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

#include <string>

int main(int argc, char *argv[]) {    
    if(argc != 2) {
        printf("usage: %s filename", argv[0]);
        return 0;
    } else {
        std::string command("cat ");
        command += argv[1];
        printf("command: %s", command.c_str());
        return system(command.c_str());
    }
}

std::string对象将根据需要动态分配内存,以容纳您添加到其中的其他字符。但是,如果您希望继续使用C字符串,则需要明确管理字符缓冲区:

char *buffer = static_cast<char*>(malloc(5 + strlen(argv[1])));
strcpy(buffer, "cat ");
strcat(buffer, argv[1]);
printf("command: %s", buffer);
// ...
free(buffer); 

答案 1 :(得分:2)

strcat调用中,您尝试修改字符串文字“cat”,这是未定义的行为。 strcat的第一个参数应该是一个可以写入的缓冲区,而不是字符串文字。

答案 2 :(得分:2)

您正在错误地使用strcat。您需要提供目标缓冲区。

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

int main(int argc, char *argv[])
{
        if(argc == 2) {
             char[20] c = "cat";
             strcat(c, argv[1]);
             printf("commad: %s", c);
             system(c);
        }
        else {
            printf("usage: %s filename", argv[0]);
        }

        return 0;
}

或不连接

printf("commad: %s%s", "cat ", argv[1]);
相关问题