使用malloc STRCPY? [英] strcpy with malloc?

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

问题描述

请告诉我,如果它是安全的,做这样的事情:

Please tell me if it is safe to do something like this:

#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 must be used?

char* msg = (char*)malloc(sizeof(char) * 15);

感谢所有!

推荐答案

您原来的code不分配味精。试图以strcpy的这将是坏的。您需要分配一些空间,你的strcpy到它。按照你的建议,你可以使用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];

如果你malloc的内存,你应该还记得在某个时候释放它。如果分配在栈上的内存会当它超出范围(例如函数退出)自动返回到堆栈中。在这两种情况下,你需要仔细分配足以能够最长的字符串复制到它。你可能想看看函数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.

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

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