错误范例如下
char *str = (char *)malloc(16);
char *hello = "hello";
str = hello + 1;
prntf("str = %s\n" , str);
free(str);
实际上要注意申请了内存的指针不能作为左值,这样会造成申请的地址无法被再次指向。
本例中应把
str = hello + 1;
改为
memcpy(str , hello , sizeof(hello));
博客指出申请了内存的指针不能作为左值,否则会使申请的地址无法被再次指向。并给出错误范例,将 'str = hello + 1;' 改为 'memcpy(str, hello, sizeof(hello));' 来解决问题。
错误范例如下
char *str = (char *)malloc(16);
char *hello = "hello";
str = hello + 1;
prntf("str = %s\n" , str);
free(str);
实际上要注意申请了内存的指针不能作为左值,这样会造成申请的地址无法被再次指向。
本例中应把
str = hello + 1;
改为
memcpy(str , hello , sizeof(hello));
1406

被折叠的 条评论
为什么被折叠?