[英]segmentation fault while passing char* as parameter - c
当我尝试将 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 ");
command = "cp .tmp.db ";
应该是strcpy(command, "cp .tmp.db ");
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.