-4

this is one of the question from 295c

#include<stdio.h>   
#include<string.h>        
main()        
{        
    char *a="kammo DJ";         
    const char *b="roomies!!";       
    char *c;         
    a=(char *)malloc(strlen(a) + strlen(b));           
    c=(char *)malloc(strlen(a) + strlen(b));          
    c=strcat(a,b);                          
    printf("%s\n",a);               
}                          

and the output is - roomies!! but why the output should be concatenation of kammo DJ + roomies!! also tell what is the value of c?

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
akash
  • 1,801
  • 7
  • 24
  • 42

3 Answers3

3

First, you should malloc the strlen(a) + strlen(b) + 1 because of the '\0' symbol. You already declared char * a = "kammo dj" so you can't allocate memory for that. When you did the malloc for char * a, it returned the location of the memory pool malloc created. if you just do:

#include<stdio.h>   
#include<string.h>
#include<malloc.h>

int main()        
{        
    const char *a="kammo DJ";         
    const char *b="roomies!!";       
    char *c;
    size_t len = strlen(a) + strlen(b) + 1;
    c=(char *)malloc(len*sizeof(char));          
    strcpy(c,a);
    strcat(c,b);      
    printf("%s\n",c);
    // don't forget!
    free(c);
    return 0;

}         

will output 'kammo DJroomies (no space between)

cybertextron
  • 10,547
  • 28
  • 104
  • 208
3

The poblem here is that when you do

a=(char *)malloc(strlen(a) + strlen(b));    

It means a is no longer pointing to "kammo DJ". Instead it is pointing to freshly allocated memory contain arbitrary data.

It appears that the first byte of the data a is now pointing to happens to be 0, which effectively makes a the empty string. Which is why you are getting just roomies!! as your result. But that is just luck.

The code you really want is:

#include<stdio.h>   
#include<string.h>        
main()        
{        
    const char *a="kammo DJ";         
    const char *b="roomies!!";       
    char *c;         
    c=(char *)malloc(strlen(a) + strlen(b) + 1);          
    strcpy(c,a);                          
    strcat(c,b);                          
    printf("%s\n",c);               
}
Sodved
  • 8,428
  • 2
  • 31
  • 43
  • Why the down-vote? This all looks correct to me and was the first accurate correction of the program posted if that's what you wanted! (You're not downvoting because it doesn't fix the main() return type and left the cast on the malloc are you? That's harsh :-/) – Rup Jul 09 '12 at 13:32
2
a=(char *)malloc(strlen(a) + strlen(b));

You need room for the terminating null character. The size of a string is its length + one byte for the null character. Also a was declared to point at the "kammo DJ" string literal. After the malloc call you make the pointer points to something else.

c=strcat(a,b);

a is not a string and contains an indeterminate value after malloc.

ouah
  • 142,963
  • 15
  • 272
  • 331