简体   繁体   中英

Dereferencing char pointer causes segfault

I am using strchr to find a point in the buffer where an = is encountered. Then I am changing that equal too character to a M . I get a segfault at the line where I try to do this.

This is the FULL code:

int main(void){
    char *buffer = "Name=Tom"
    char *pointer;
    pointer = strchr(buffer,'=');
    *pointer = 'M';    <--------- Segfault Occurs here
return (0);
}

I get the following error with the segfault:

Process terminating with default action of signal 11 (SIGSEGV)
 Bad permissions for mapperd region at addresss .....

You are not checking the return value of strchr , it could be NULL since we don't see your input.

In addition to this, where and how is buffer declared? not all char* can be modified, since they could be stored in data segment of the binary (as a string literal).

You are attempting to modify the value of a string literal which will be stored in a read only memory segment. This results in an access violation.

The problem is here:

char *buffer = "Name=Tom";

Modify it to be:

char buffer[] = "Name=Tom";

What you are doing here is wrong:

char *buffer = "Name=Tom";

When you assign a string literal to a pointer it is stored as a const char* , which cannot be modified, which is what you are trying to do later in your code.

Here, you first need to allocate memory to buffer and then use strcpy to copy the contents like:

char buffer[100];
strcpy(buffer, "Name=Tom");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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