'strcpy'与“malloc”?
执行以下操作安全吗?
#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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
strdup 为您执行 malloc 和 strcpy
strdup does the malloc and strcpy for you
您的原始代码没有分配 msg。尝试对其进行 strcpy 会很糟糕。在 strcpy 之前,您需要分配一些空间。您可以按照您的建议使用 malloc 或像这样在堆栈上分配空间:
如果您 malloc 内存,您应该记住在某个时候释放它。如果在堆栈上分配内存,当超出范围(例如函数退出)时,内存将自动返回到堆栈。在这两种情况下,您都需要小心分配足够的空间,以便能够将最长的字符串复制到其中。您可能需要查看 strncpy 以避免数组溢出。
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:
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.
第一个版本不安全。并且,
msg
应该指向“Hello World!!!”的有效内存位置。被复制。The first version is not safe. And,
msg
should be pointing to valid memory location for "Hello World!!!" to get copied.使用:
现在它很简单并且符合标准:
Use:
And now it's easy and standard conforming:
这是UB。没有第二个想法。
msg
是一个野指针,尝试取消引用它可能会导致您的实现出现段错误。msg
指向一个足够大的有效内存位置以容纳“Hello World”。
尝试
或
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
or
您需要分配空间。在
strcpy
之前使用malloc
。You need to allocate the space. Use
malloc
before thestrcpy
.