Home > Net >  Right methods of copying strings with malloc
Right methods of copying strings with malloc

Time:11-10

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”))

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.

CodePudding user response:

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.

CodePudding user response:

Use of sizeof id limited to only this one case (string literal). Ti will not work if you will have a pointer referencing the string. Before you start to be more proficient in C language and "feel" the difference between arrays and pointers IMO you should always use strlen

Example:

char *duplicateString(const char *str)
{
    char *newstring = malloc(strlen(str)   1);
    if(newstring) strcpy(newstring, str);
    return newstring;
}

In this case, sizeof(str) would give the size of the pointer to char (usually 2, 4 or 8) not the the length of the string referenced by the str

  • Related