gpt4 book ai didi

c - 传递 char* 作为参数时出现段错误 - c

转载 作者:行者123 更新时间:2023-11-30 20:48:42 25 4
gpt4 key购买 nike

当我尝试传递 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 是否成功,我稍后会添加它,我想先解决这个问题。

最佳答案

当您执行以下操作时

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 ");

关于c - 传递 char* 作为参数时出现段错误 - c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com