'strcpy' with 'malloc'?

LEH picture LEH · Mar 18, 2011 · Viewed 42k times · Source

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

Answer

pm100 picture pm100 · Mar 18, 2011

strdup does the malloc and strcpy for you

char *msg = strdup("hello world");