''strcpy' with 'malloc'?
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);
Solution 1:[1]
strdup does the malloc and strcpy for you
char *msg = strdup("hello world");
Solution 2:[2]
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!!!");
Solution 3:[3]
Use:
#define MYSTRDUP(str,lit) strcpy(str = malloc(strlen(lit)+1), lit)
And now it's easy and standard conforming:
char *s;
MYSTRDUP(s, "foo bar");
Solution 4:[4]
You need to allocate the space. Use malloc before the strcpy.
Solution 5:[5]
char* msg;
strcpy(msg, "Hello World!!!"); //<---------Ewwwww
printf("%s\n", msg);
This is UB. No second thoughts. msg is a wild pointer and trying to dereference it might cause segfault on your implementation.
msg to be pointing to a valid memory location large enough to hold "Hello World".
Try
char* msg = malloc(15);
strcpy(msg, "Hello World!!!");
or
char msg[20];
strcpy(msg, "Hello World!!!");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
| Solution 2 | |
| Solution 3 | Peter Mortensen |
| Solution 4 | SDReyes |
| Solution 5 | Prasoon Saurav |
