Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Right methods of copying strings with malloc

I want to copy the string “Best School” into a new space in memory, which of these statements can I use to reserve enough space for it

A. malloc(sizeof(“Best School”))

B. malloc(strlen(“Best School”))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C. malloc(11)

D. malloc(12)

E. malloc(sizeof(“Best School”) + 1)

F. malloc(strlen(“Best School”) + 1)

I am still very new to C programming language so I really am not too sure of which works well. But I will love for someone to show me which ones can be used and why they should be used.

Thank you.

>Solution :

Literal strings in C are really arrays, including the null-terminator.

When you use sizeof on a literal string, you get the size of the array, which of course includes the null-terminator inside the array.

So one correct way for a literal string would be sizeof("Best School") (or sizeof "Best School").

You can also use strlen. If you don’t have a string literal but another array or a pointer to the first character of the string, then you must use strlen. But now you have to remember that strlen returns the length of the string without the null-terminator. So you need to add one for that.

So another correct way would then be strlen("Best School") + 1.

Using magic numbers is almost never correct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading