Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault occurring when modifying a string using pointers?

Context

I'm learning C, and I'm trying to reverse a string in place using pointers. (I know you can use an array; this is more about learning about pointers.)

Problem

I keep getting segmentation faults when trying to run the code below. GCC seems not to like the *end = *begin; line. Why is that?

Especially since my code is nearly identical to the non-evil C function already discussed in another question

#include <stdio.h>
#include <string.h>

void my_strrev(char* begin){
    char temp;
    char* end;
    end = begin + strlen(begin) - 1;

    while(end>begin){
        temp = *end;
        *end = *begin;
        *begin = temp;
        end--;
        begin++;
    }
}

main(){
    char *string = "foobar";
    my_strrev(string);
    printf("%s", string);
}
like image 849
brice Avatar asked Jan 23 '10 20:01

brice


People also ask

What causes segmentation fault with pointers?

A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.

What are three kinds of pointers that can cause a segmentation fault?

Causes of segmentation fault:Attempting to access a nonexistent memory address (outside process's address space). Attempting to access memory the program does not have rights to (such as kernel structures in process context). Attempting to write read-only memory (such as code segment).

What is the common issue that would cause a segmentation fault when using character strings in C?

The segfault happens when you try to change the first character to 'z' . Whenever using "%p" on printf, you should cast the pointer to void * as in printf("%p", (void *)str); When printing a size_t with printf, you should use "%zu" if using the latest C standard (C99).

Does dangling pointer cause segmentation fault?

If the memory has been reallocated to another process, then attempting to dereference the dangling pointer can cause segmentation faults (UNIX, Linux) or general protection faults (Windows).


1 Answers

One problem lies with the parameter you pass to the function:

char *string = "foobar";

This is a static string allocated in the read-only portion. When you try to overwrite it with

*end = *begin;

you'll get the segfault.

Try with

char string[] = "foobar";

and you should notice a difference.

The key point is that in the first case the string exists in the read-only segment and just a pointer to it is used while in the second case an array of chars with the proper size is reserved on the stack and the static string (which always exists) is copied into it. After that you're free to modify the content of the array.

like image 157
Remo.D Avatar answered Sep 20 '22 20:09

Remo.D