Question

What is wrong with the following code fragment? char *src = "hello"; char *dst = (char...

What is wrong with the following code fragment?

char *src = "hello";

char *dst = (char *) malloc(strlen(src)); //too small!

strcpy (dst, src); //work properly

0 0
Add a comment Improve this question Transcribed image text
Answer #1

char *src = "hello";
char *dst = (char *) malloc(strlen(src)); //too small!      <-  this line is the issue.
strcpy (dst, src); //work properly

strlen(src) gives a value of 5. because there are 5 characters in string "hello"
but there is also a hidden character of '\0', which indicates the end of a string.
so, to copy the string src into dst properly, we need to allocate one extra character to hold the end of the string character.
so, line 2 should be changed to the code below.
char *dst = (char *) malloc(1+strlen(src));

Modified code:
---------------
char *src = "hello";
char *dst = (char *) malloc(1 + strlen(src));
strcpy (dst, src);


Add a comment
Know the answer?
Add Answer to:
What is wrong with the following code fragment? char *src = "hello"; char *dst = (char...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT