且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用malloc STRCPY?

更新时间:2022-03-25 00:28:31

您原来的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.