我在尝试释放内存时遇到了一些错误。下面发布了我的所有代码。 我正在使用 ubuntu 并使用 gcc 编译我的代码。但是当我尝试执行代码时,在尝试释放内存时出现错误。 我在我的代码上添加了注释来解释我的疑问。我正在使用堆栈结构。 如何在不出错的情况下释放内存以将释放内存转换为字符? 如果我不释放分配给数据(字符)的内存,而只释放元素(包含字符数据)的内存,那么分配给数据的内存会发生这种情况?免费吗?
错误
{
*** glibc detected *** ./pilha: free(): invalid next size (fast): 0x08b86018 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x74f82)[0xb7637f82]
./pilha[0x80485ba]
./pilha[0x804864c]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0xb75dc4d3]
./pilha[0x8048411]
======= Memory map: ========
}
<小时/>
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Stack_element{
char *data;
struct Stack_element *next;
}Element;
typedef struct Position{
Element *top;
int size;
}stack;
void start(stack *aux){
aux->top = NULL;
aux->size = 0;
}
int push(stack *aux, char value){
Element *new_element;
if ((new_element = (Element*) malloc(sizeof(Element))) == NULL)
return -1; //an error occur
if ((new_element->data = (char*) malloc(sizeof(char))) == NULL)
return -1; //an error occur
strcpy(new_element->data, &value);
new_element->next = aux->top;
aux->top = new_element;
aux->size++;
}
int empty(stack *aux){
if ((aux->size) == 0){
return -1;
}
return 0;
}
char pop(stack *aux){
Element *element;
char value='0';
if (empty(aux)){
return '1';
}
element = aux->top;
aux->top = aux->top->next;
/*
To observe the line below. When a element exist in the stack and
I try remove this element, first I free the data in that node (element)
so I turn free memory allocated for the element.
If I didn't free data memory allocated before (in push fuction), I
don't get any error. But the memory allocated for the data, what happens?
Does is it continues allocated?
*/
value = *(element->data);
free(element->data);//THE ERROR OCCURS HERE, IN THIS LINE
free(element);//Just after free the data element memory, I also free the element's memory
aux->size--;
return value;
}
int main(){
stack p;
char value;
start(&p);
//no error occurs. there isn't any element at this moment.
printf("%c\n",pop(&p));
//valor = 't';
if (push(&p, 't')){
printf("Add a char\n");
}
pop(&p);//the error occurrs now, after insert an new element in the stack
printf("The End.");
}
最佳答案
在您的代码中,
strcpy(new_element->data, &value);
不正确。您只为一个 char
分配了内存,而该字符没有空间用于空终止符。相反,你应该使用
*(new_element->data) = value;
否则,如果 strcpy()
使用不当,您会因内存溢出而弄乱分配的内存,从而导致 undefined behaviour .
关于c - 尝试释放内存时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30023471/