c - Segmentation fault occurring when modifying a string using pointers? -
context
i'm learning c, , i'm trying reverse string in place using pointers. (i know can use array; more learning pointers.)
problem
i keep getting segmentation faults when trying run code below. gcc seems not *end = *begin; line. why that?
especially since code identical the non-evil c function discussed in 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); }      
one problem lies parameter pass function:
char *string = "foobar";   this static string allocated in read-only portion. when try overwrite
*end = *begin;   you'll segfault.
try with
char string[] = "foobar";   and should notice difference.
the key point in first case string exists in read-only segment , pointer used while in second case array of chars proper size reserved on stack , static string (which exists) copied it. after you're free modify content of array.
Comments
Post a Comment