C语言 “strcpy”与“malloc”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5354933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:06:12  来源:igfitidea点击:

'strcpy' with 'malloc'?

cmallocstrcpy

提问by LEH

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

采纳答案by qbert220

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:

您的原始代码未分配 msg。试图对它进行 strcpy 将是不好的。您需要在 strcpy 之前分配一些空间。您可以按照建议使用 malloc 或像这样在堆栈上分配空间:

char msg[15];

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.

如果你 malloc 内存,你应该记得在某个时候释放它。如果你在栈上分配内存,当它超出作用域(例如函数退出)时,它会自动返回到栈中。在这两种情况下,您都需要小心分配足够的空间,以便能够将最长的字符串复制到其中。您可能需要查看 strncpy 以避免数组溢出。

回答by pm100

strdup does the malloc and strcpy for you

strdup 为你做 malloc 和 strcpy

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

回答by user411313

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

回答by Mahesh

The first version is not safe. And, msgshould be pointing to valid memory location for "Hello World!!!" to get copied.

第一个版本不安全。并且,msg应该指向“Hello World!!!”的有效内存位置 被复制。

char* msg = (char*)malloc(sizeof(char) * 15);
strcpy(msg, "Hello World!!!");

回答by SDReyes

You need to allocate the space. Use mallocbefore the strcpy.

您需要分配空间。使用mallocstrcpy

回答by Prasoon Saurav

 char* msg;
 strcpy(msg, "Hello World!!!");  //<---------Ewwwww
 printf("%s\n", msg); 

This is UB. No second thoughts. msgis a wild pointer and trying to dereference it might cause segfault on your implementation.

这是 UB。没有第二个想法。msg是一个野指针,尝试取消引用它可能会导致您的实现出现段错误。

msgto be pointing to a valid memory location large enough to hold "Hello World".

msg指向一个足够大的有效内存位置 "Hello World".

Try

尝试

char* msg = malloc(15);
strcpy(msg, "Hello World!!!");

or

或者

char msg[20]; 
strcpy(msg, "Hello World!!!");