'strcpy'与'malloc'吗? [英] 'strcpy' with 'malloc'?

查看:164
本文介绍了'strcpy'与'malloc'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作是否安全?

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

推荐答案

您的原始代码未分配msg.试图str之以鼻是不好的.您需要分配一些空间,然后再尝试使用它.您可以按照建议使用malloc或在堆栈上分配空间,如下所示:

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:

char msg[15];

如果您分配了内存,则应记住在某个时候释放它.如果您在堆栈上进行分配,则当内存超出范围时(例如函数退出),内存将自动返回到堆栈中.在这两种情况下,您都需要小心分配足够的空间,以便能够将最长的字符串复制到其中.您可能要看一下strncpy,以避免数组溢出.

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.

这篇关于'strcpy'与'malloc'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆