Is it safe to do something like the following?
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char* msg;
strcpy(msg, "Hello World!!!"); //<---------
printf("%s\n", msg);
return 0;
}
Or should the following be used?
char* msg = (char*)malloc(sizeof(char) * 15);
The following example allocates space for a key using malloc() then uses strcpy() to place the key there. Then it allocates space for data using malloc(), and uses strcpy() to place data there. (The user-defined function dbfree() frees memory previously allocated to an array of type struct element *.)
No, strcpy knows nothing about memory, so your code copies a string into an uninitialized pointer pointing at la-la land.
The strncpy function is a safer version of strcpy to copy a string from a source to a destination buffer. It takes three arguments, its third argument (n) is the maximum number of characters to copy.
strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.
strdup does the malloc and strcpy for you
char *msg = strdup("hello world");
Your original code does not assign msg. Attempting to strcpy to it would be bad. You need to allocate some space before you strcpy into it. You could use malloc as you suggest or allocate space on the stack like this:
char msg[15];
If you malloc the memory you should remember to free it at some point. If you allocate on the stack the memory will be automatically returned to the stack when it goes out of scope (e.g. the function exits). In both cases you need to be careful to allocate enough to be able to copy the longest string into it. You might want to take a look at strncpy to avoid overflowing the array.
The first version is not safe. And, msg
should be pointing to valid memory location for "Hello World!!!" to get copied.
char* msg = (char*)malloc(sizeof(char) * 15);
strcpy(msg, "Hello World!!!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With