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);
malloc
, but remove the cast andsizeof(char)
. The correct usage ischar *msg = malloc(15);
– Hungmalloc()
is declared in<stdlib.h>
not<malloc.h>
– Protractilemalloc()
should ALWAYS be checked:char *msg = malloc(15); if (msg == NULL) /* not ok to proceed */;
– ProtractileNULL
is malloc's way of telling you something went wrong. – Protractilesizeof(char)
is OK in this instance (as in @R..'s comment): This question explains thatsizeof(char)==1
per the C99 standard. – Genro