我试图弄清楚如何在C中正确使用malloc,并且遇到了我遇到问题的错误。
我的代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
char * str;
str = (char *)malloc(10);
str = "Hello World";
str[0] = 'R';
return EXIT_SUCCESS;
}
我的Valgrind输出:
==23136== Process terminating with default action of signal 10 (SIGBUS)
==23136== Non-existent physical address at address 0x100000F92
==23136== at 0x100000F66: main (test.c:12)
我知道问题是由于我试图将字母'R'分配给str
,但给我的印象是,malloc
在这种情况下(相对于char str[10] = "Hello World"
)使用的好处是能够编辑字符串的内容。
谢谢!
str = "Hello World";
品牌str
指向一个字符常量字符串“Hello World”,并且您已经malloced内存将成为内存泄漏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句