c - char *str and malloc'ing the memory for str, still getting SEGFAULT -
i have written small c program reverse string. in though, declare str
as
char *str
, then
str = (char*)malloc(20); str = "this test";
however, wont segfault if use
char str[20] = "this test"
#include <stdio.h> #include <stdlib.h> #include <string.h> void swap(char *a, char *b) { char temp; temp = *a; *a = *b; *b = temp; } char* reverse(char *str) { int len = strlen(str); printf("len = %d \t %s\n", len, str); int = 0; if (len == 0) return null; (i=0; i<len/2; i++) { swap((str+i), (str+len-1-i)); printf("%s\n", str); } return str; } int main(void) { char *str; str = (char *)malloc(20); str = "this test"; printf("%s\n", str); reverse(str); printf("%s\n", str); return 0; }
my understanding segfault, if declare,
char *str="this test"
becuase constant string.
so, thought, when, malloc, str
allocated heap , heap memory accessible both functions. but, still segfault error.
when do
str = (char*)malloc(20); str = "this test";
you reassign pointer str
point somewhere else right after allocation.
in fact make point string literal, array of read-only characters. attempting modify string literal leads undefined behavior.
the simple solution use arrays instead. or copy memory allocate using strcpy
.
Comments
Post a Comment