Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings with malloc in C

Tags:

c

I am writing a very simple program to copy a string using malloc.

#include <stdio.h> 
#include <stdlib.h> 

char * copyStr(char s[])
    {
      int len = strlen(s); //find length of s
      char * copy; 
      copy = (char *)malloc(len); //dynamically allocate memory 
      int i; 
      for(i=0;i<len;i++) 
       {
         copy[i]=s[i];  //copy characters               
       }
       return copy; //return address
    }

int main(int argc, char ** argv)
    {
     char * str;
     str = "music is my aeroplane";
     char * res;
     res = copyStr(str);
     printf("The copied string is : %s",res);
     getch();
    }

The desired output is:

The copied string is : music is my aeroplane

The current output is:

The copied string is : music is my aeroplaneOMEeJ8«≤╝

Any advice is appreciated.

like image 999
Arjun Avatar asked May 22 '26 04:05

Arjun


1 Answers

A C string is null terminated. Add a null character (ie the char which ASCII code is 0) at end of the string :

char * copyStr(char s[])
{
  size_t len = strlen(s); //find length of s
  char * copy; 
  copy = (char *)malloc(len + 1); //dynamically allocate memory
                           /* One more char must be allocated for the null char */

  size_t i; 
  for(i=0;i<len;i++) 
   {
     copy[i]=s[i];  //copy characters               
   }
   copy[i] = '\0'; // HERE
   return copy; //return address
}

It is better to use size_t for the lengths because it is unsigned.

like image 119
Boiethios Avatar answered May 23 '26 19:05

Boiethios



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!