user2713461 user2713461 - 3 years ago 88
C Question

char *str and malloc'ing the memory for str, still getting SEGFAULT

I have written a small C program to reverse a string.
In this even though, I declare the


char *str

and then

str = (char*)malloc(20);
str = "this is a test";

However, I wont get SEGFAULT if I use

char str[20] = "this is a 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 i = 0;

if (len == 0)
return NULL;
for (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 is a test";

printf("%s\n", str);
printf("%s\n", str);
return 0;

My understanding was I will get SEGFAULT, if I declare,

char *str="This is a test"
becuase it will be a constant string.

So, I thought, when, I malloc,
will be allocated from the heap and heap memory will accessible to both the functions. But,
still get the SEGFAULT error.

Answer Source

When you do

str = (char*)malloc(20);
str = "this is a test";

you reassign the pointer str to point somewhere else right after the allocation.

In fact you make it point to a string literal, which is an array of read-only characters. Attempting to modify a string literal leads to undefined behavior.

The simple solution is to use arrays instead. Or to copy into the memory you allocate using strcpy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download