If I want to copy the string "Best School" into a new space in memory in C programming, What statement(s) can I use to reserve enough space for it?
I have tried using this:
malloc(strlen("Best School") + 1)
And this also
malloc(sizeof("Best School"))
The simplest and safest way to allocate a block of memory and copy a null terminated string into it is:
strdup()is declared in<string.h>, has been part of the POSIX Standard since its inception and finally made it into Standard C as of C23. It is available on most systems and can be defined this way:Alternately, you could use
malloc,strlenandstrcpydirectly:mallocallocates a block memory of a given size. The memory is uninitialized, its contents are indeterminate, so if the allocation was successful, you must then copy the string into it, including the null terminator ('\0')."Best school"is a null terminated string with 12 bytes: 11 characters plus a null terminator byte.And for string literals, you could even use
sizeof:But both of the above solutions are error prone because:
"Best school"may return a block of 16 bytes and the 12th byte may happen to be a null byte, especially if this memory has not been used before. This kind of undefined behavior is sly and will bite at the worst time.sizeofversion only works for string literals! If you want to allocate a copy of a string you only have a pointer to,sizeof(ptr)will evaluate to the size of the pointer, not that of the string, leading to undefined behavior for all but the shortest strings. This solution works for the example in the question, but should be disregarded.The recommended solution is
strdup.