繁体   English   中英

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

[英]segmentation fault in a simple command line program

我正在尝试创建一个简单的程序,在作为命令参数输入的文件位置上使用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;
}

您不能修改字符串文字,例如"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); 

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

您使用的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]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM