John Doe February 2016

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 .....

Answers


Jack February 2016

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).


David Hoelzer February 2016

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


Ahmed Akhtar February 2016

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

Post Status

Asked in February 2016
Viewed 2,495 times
Voted 7
Answered 3 times

Search




Leave an answer