mr.loop
mr.loop

Reputation: 1005

Unexpected memory allocation by malloc

here's a code that allocates some memory and copies a string into it.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
  
int main(){
   char *t ="your_char";

   char *s = (char*)malloc(9);
                                                                                                                                    
   memcpy(s,t,9); 

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

now the output is

your_char
your_char☺╚

And that is what I am unable to understand. If I change to memcpy(s,t,10), then there is no garbage value at the end.

I assume it is because of null terminator that also gets copied in second case. But why is there an empty place at all when I have only allocated 9 bytes and they are already occupied by the characters I copied.

Upvotes: 0

Views: 100

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 120229

A string is a null terminated array of characters (a "null character" is the one that has the numeric value of 0). The null character marks the end of the string, If an array doesn't have a null character in it, it is not a string. In particular, you cannot printf it with the %s specifier, because printf has no idea where it ends.

String literals always have one automatically, for example, "your_char" has ten characters in it and not nine. If you allocate strings dynamically, you should always account for the extra character.

Upvotes: 2

Related Questions