为什么 C 中的 free() 不起作用?


int main()
{
    char* in = (char *)malloc(sizeof(char)*100);
    in = "Sort of Input String with LITERALS AND NUMBERS";
    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]

因为in是由in = "Sort of ...";重新分配的。

实际上,你正在做free("Sort of ...");,这显然是非法的。

in是一个指针。 你用malloc()设置它,稍后你把它更改为指向文字。 然后,您尝试将此 poitner 释放到一个垃圾(从未在堆上分配过,因此会导致free()失败(。

要复制字符串,您必须使用 strcpy()

char* in = malloc(sizeof(char)*100);
strcpy (in, "Sort of Input String with LITERALS AND NUMBERS");
free(in);

实际上,为了避免意外的缓冲区溢出,您还可以复制字符串,将其最大长度纳入 conside:

strncpy (in, "Sort of Input String with LITERALS AND NUMBERS", 100);

最新更新