【发布时间】:2014-09-17 10:30:24
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char* a = malloc(5 * sizeof(char));
a = "1";
free(a);
}
我对上述代码有两个问题:
- 当我像这样初始化 a 时,为什么代码会在 free(a) 中出现错误:
a = "1"
当我像这样初始化 a 时,free(a) 没有任何错误:
a[0] = '1'。
- 当我用
a[0] = '1'
并使用打印字符串 a
printf("%s", a) 为什么我得到结果
'1'
【问题讨论】:
-
a = "1";不会用 a 填充 a,它会将指针重新分配给内存中的某个字符串“a”。该字符串已编译和修复,不能/不应该被释放。
-
从字面上看,只要 C 程序执行此操作:
Type* p = malloc(...); p = ...就错了。您的程序在前两行中泄漏了内存,然后释放了只读字符串文字的地址.. -
关于 '\0' 的第二个索引。这纯粹是运气,因为内存中包含“\0”。
标签: c string pointers memory malloc