1

while this Code works:

 char * k = "asd"; 
 char * j = malloc(sizeof(char) * 3);
 memmove(j,k,3);
 printf("%s",j);

while code gives error:

 char * k = "asd";
 char * j = malloc(sizeof(char) * 3);
 memmove(k,k+1,3);
 printf("%s",k); // output should be "sd"

I am thinking wrong? Why it gives an erorr? I'm planning to use it for deleting the multiple whitespaces ("aaa.......bbb"(dots are spaces) -> "aaa bbb")

Thank you.

Batuhan Yaman
  • 25
  • 1
  • 1
  • 5
  • The above code is bogus and works just by luck. You are not copying the trailing `\0`. So the string j has no terminating `\0`. In the second code you are modifying the global constant "asd" which is bad. – chmike Mar 19 '15 at 15:04

3 Answers3

1

A declaration like

char *k = "asd";

causes the string literal to be stored in the read-only data segment. (C compilers tend to not warn for this case even though declaring the pointer as const char *k = "asd" would be safer, for historical reasons.)

If you want the string contents to be modifiable, you will need to use an array instead, like

char k[] = "asd";
Ulfalizer
  • 4,664
  • 1
  • 21
  • 30
0

The statement

memmove(k,k+1,3);  

tries to shift the elements of string literal asd by 1. String literals are non modifiable. Any attempt to modify it will invoke undefined behavior.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

When you do char *k = "asd", the string "asd" is placed in the read only parts of memory and the pointer k is made to point there. You cannot write to this location using memmove().

You should instead use char k[] = "asd".

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34