gpt4 book ai didi

c - "pointer being freed was not allocated"到底是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 16:31:32 25 4
gpt4 key购买 nike

我在尝试将字符串复制到 c 中的结构字符串变量的程序时遇到问题。复制字符串后,我试图释放复制到结构字符串变量的临时字符串变量。但是当我尝试释放字符串时,程序打开我并说“未分配正在释放的指针”。我不明白到底发生了什么。

char str[]="       ";           //temporary string to copy to structs string
str[3]=s; //putting a char s in middle
strcpy(matrix[i-1][j].c, str); //copying the string
free(str); //freeing str that now is useless when copied

最佳答案

只有通过调用 malloc()realloc()calloc() 返回的指针才能传递给 free( )(在堆上动态分配内存)。摘自7.20.3.2 C99 标准的自由函数:

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

贴出的代码中,str不是动态分配的,而是在栈上分配的,超出作用域时自动释放,不需要free()d.

关于c - "pointer being freed was not allocated"到底是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com