int main()
{
char* in = (char *)malloc(sizeof(char)*100);
in = "Sort of Input String with LITERALS AND NUMBERS\0";
free(in);
return 0;
}
为什么此代码不能处理此错误?
pointers(10144,0x7fff78a82000) malloc: *** error for object 0x10ba18f88: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
bash: line 1: 10144 Abort trap: 6 '/Users/.../Documents/term2_sr/pointers'
[Finished in 0.1s with exit code 134]
答案 0 :(得分:3)
由in
重新分配in = "Sort of ...";
。
实际上,你正在做free("Sort of ...");
,这显然是非法的。
答案 1 :(得分:2)
in
是一个指针。您使用malloc()
进行设置,稍后将其更改为指向文字。然后你尝试将这个poitner释放到一个litteral(它从未在堆上分配,因此导致free()
失败)。
要复制字符串,您必须使用strcpy()
:
char* in = malloc(sizeof(char)*100);
strcpy (in, "Sort of Input String with LITERALS AND NUMBERS");
free(in);
实际上,为了避免意外的缓冲区溢出,你也可以复制字符串,考虑到它的最大长度:
strncpy (in, "Sort of Input String with LITERALS AND NUMBERS", 100);