简体   繁体   English

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

[英]segmentation fault while passing char* as parameter - c

I'm having problems when I try to pass a char* as an argument, my code is like that:当我尝试将 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
}

I'm running it with ./program base.db , and output is like that:我用./program base.db运行它,输出是这样的:

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

And then it just fails: Segmentation fault.然后它就失败了:分段错误。 I'm sure this is the line which is crashing because I run it with gdb, but I'm not sure what I'm doing wrong.我确定这是崩溃的线路,因为我用 gdb 运行它,但我不确定我做错了什么。 I also tried to print base[i], with a for loop, but it has the same effect.我还尝试使用 for 循环打印 base[i],但效果相同。 I looked up other questions, but I can't solve this.我查了其他问题,但我无法解决这个问题。

I know I should see if malloc was successful, I'll add it latter, I want to solve this first.我知道我应该看看malloc是否成功,我会在后面添加它,我想先解决这个问题。

When you do the following当您执行以下操作时

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

Later, here后来这里

strcat(command,base);

You are trying to concat to the read only memory.您正在尝试连接到只读内存。


To correct this, use strcpy()要纠正此问题,请使用strcpy()

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

command = "cp .tmp.db "; should be strcpy(command, "cp .tmp.db ");应该是strcpy(command, "cp .tmp.db ");

strcat appends copy of source string to the destination string, so destination should have enough of memory. strcat 将源字符串的副本附加到目标字符串,因此目标应该有足够的内存。

You allocated memory for the command variable, but then assigned literal value to it, so command stores pointer to the read only memory.您为命令变量分配了内存,但随后为其分配了文字值,因此命令存储指向只读内存的指针。

Modify your code like this:像这样修改你的代码:

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.

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