传递char *作为参数时的分段错误 - c

时间:2015-11-10 06:10:19

标签: c memory

当我尝试将char *作为参数传递时,我遇到了问题,我的代码是这样的:

int main(int argc, char** argv ) {
    if(argc > 1) {
        //not sure if I need this..
        char* base = malloc(strlen(argv[1]) + 1);
        strcpy(base, argv[1]);
        base[strlen(argv[1])] = '\0';

        printf("base is %s\n", base); //does it right

        testFunction(base);

        return 0;
    } else {
        //do something
    }
};

void testFunction(char* base) {
    //do things
    anotherFunction(base);
};

void anotherFunction(char* base) {
    char* command = malloc(52);
    command = "cp .tmp.db ";
    printf("Command before cat %s, base is   %s\n", command, base);
    strcat(command, base); //Segmentation fault
    printf("Command I need %s\n", command);
    //more things
}

我用./program base.db运行它,输出就是这样:

base is base.db
Command before cat cp .tmp.db, base is  base.db

然后它就失败了:分段错误。我确定这是崩溃的线路,因为我用gdb运行它,但我不确定我做错了什么。我也尝试使用for循环打印base [i],但它具有相同的效果。 我查了解其他问题,但我无法解决这个问题。

我知道我应该看看malloc是否成功,我会在后面添加它,我想先解决这个问题。

3 个答案:

答案 0 :(得分:3)

当您执行以下操作时

char* command = malloc(52);  //this memory is wasted
command = "cp .tmp.db ";    //this is string constant, and is kept in read only memory

稍后,这里

strcat(command,base);

您正在尝试连接到只读内存。

要更正此问题,请使用strcpy()

char* command = malloc(52);
strcpy(command, "cp .tmp.db ");

答案 1 :(得分:1)

command = "cp .tmp.db ";应为strcpy(command, "cp .tmp.db ");

答案 2 :(得分:0)

strcat将源字符串的副本附加到目标字符串,因此目标应该有足够的内存。

您为命令变量分配了内存,但随后为其分配了文字值,因此命令将指针存储到只读内存。

像这样修改你的代码:

char* command = (char*)calloc(128, sizeof(char));
strcpy(command, "cp .tmp.db ");
printf("Command before cat %s, base is   %s\n",command,base);
strcat(command,base);
printf("Command I need %s\n",command);
相关问题