【发布时间】:2011-07-18 07:36:06
【问题描述】:
执行以下操作是否安全?
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void)
{
char* msg;
strcpy(msg, "Hello World!!!"); //<---------
printf("%s\n", msg);
return 0;
}
还是应该使用下面的?
char* msg = (char*)malloc(sizeof(char) * 15);
【问题讨论】:
-
你需要 malloc,否则 msg 只是一个悬空指针。
-
使用
malloc,但删除演员表和sizeof(char)。正确用法是char *msg = malloc(15); -
另外
malloc()是在<stdlib.h>而不是<malloc.h>中声明的 -
并且应该始终检查来自
malloc()的返回值:char *msg = malloc(15); if (msg == NULL) /* not ok to proceed */; -
@MateuszPiotrowski:如果你不检查,你就无法知道它是否“有效”。返回
NULL是 malloc 告诉您出现问题的方式。