-3

Possible Duplicate:
Modifying C string constants?

What is the difference between char *str when using malloc or not?

int i;
char *s =  (char*)malloc(sizeof(char)*27); 
for(i=0;i<26;i++)
  s[i]='a'+i;
s[26]='\0';
printf("%s\n",s);
reverse(s);
printf("%s\n",s);

where reverse() is

void reverse(char *str)
{
  int i,j=strlen(str)-1;
  char tmp;
  for(i=0;i<j;i++,j--)
  {
    tmp=str[i];
    str[i]=str[j];
    str[j]=tmp;
  }   
}

This works fine but when using

char *t = "new string";
printf("%s\n",t);
reverse(t);
printf("%s\n",t);

I get a segfault and the debugger says it is in strlen in reverse. Changing char *t to char t[] works fine. What gives?

Community
  • 1
  • 1
Mike
  • 3
  • 1
  • 2
    Duplicates: http://stackoverflow.com/questions/2124600/how-to-reverse-a-string-in-place-in-c-using-pointers http://stackoverflow.com/questions/480555/modifying-c-string-constants http://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c http://stackoverflow.com/questions/164194/why-does-simple-c-code-receive-segmentation-fault – nos Nov 26 '11 at 00:05

1 Answers1

5

That's normal:

char * t = "new string";

t points to a string literal. Modifying it causes undefined behavior, and most implementations store such literals in a read-only memory section. In your case, you got a segfault, but sometimes it will look like as if it worked.

char *s =  (char*)malloc(sizeof(char)*27); 

This allocates a new block of memory. Since that memory belongs to you, you're free to do as you please with it.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111