malloced指针中的内存泄漏?

时间:2017-06-27 03:47:47

标签: c pointers memory memory-leaks

我得到了两个内存泄漏的例子,我似乎无法解决。第一个实例来自dataWithContentsOfURL:,我在if语句的开头使用这个变量,并确保在结束时释放它,但我仍然得到泄漏。第二种情况发生在char *temp = (char*)malloc(sizeof(char*));s = create();

s = (Stack*)malloc(sizeof(Stack));

我无法弄清楚#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ char **data; int top; int size; }Stack; typedef enum { FALSE, TRUE } bool; Stack* create(){ Stack *s; s = (Stack*)malloc(sizeof(Stack)); s->top = -1; s->size = 10; s->data = (char**)malloc(s->size*sizeof(char*)); return s; } void deleteStack(Stack* ps){ if(ps == NULL){ printf("No memory allocated in Stack.\n"); } while(ps->top >= 0){ free(ps->data[ps->top]); ps->top--; } free(ps->data); } bool full( Stack s){ if(s.top == s.size-1) return TRUE; return FALSE; } void push( Stack* ps, char* str){ if(full(*ps)){ int tempsize = ps->size; ps->size += 10; ps->data = realloc(ps->data, ps->size * sizeof(char*)); // char **temp = realloc(ps->data, ps->size*sizeof(char*)); // if(temp == NULL){ // perror("realloc"); // printf("Error! memory not allocated.\n"); // exit(-1); // } // ps->data = temp; printf("Stack capacity has grown from %d elements to %d elements\n", tempsize, ps->size); } ps->data[++ps->top] = strdup(str); } bool empty( Stack s){ if(s.top == -1) return TRUE; return FALSE; } char* pop( Stack* ps){ if(empty(*ps)) return NULL; return ps->data[ps->top--]; } int main(int argc, char *argv[]){ printf("Assignment 2 Problem 1 by Jasmine Ramirez\n\n"); FILE *input = fopen("data_a2.txt", "r"); if(input == NULL){ perror("fopen"); printf("File %s not found.\n", "data_a2.txt"); exit(EXIT_FAILURE); } Stack *s; s = create(); <---16 bytes in 1 block definitely lost char str[255]; char *temp = (char*)malloc(sizeof(char)); <---1 bytes in 1 block definitely lost int i = 0; while(fscanf(input, "%s\n", str) == 1){ if(strcmp(str, "pop") == 0){ temp = pop(s); i--; printf("# of elements after popping: %d\tstring popped: %s\n", i, temp); free(temp); } else{ push(s, str); i++; } } deleteStack(s); fclose(input); return 0; } 中丢失1个字节的原因temp s应该由deleteStack()处理。

2 个答案:

答案 0 :(得分:3)

在此声明中

temp = pop(s);

指向早期malloced内存的指针丢失,因此泄露。

deleteStack中,您尚未释放ps,因此也会泄漏,因为Stack *s;中分配给create的内存永远不会被释放。

答案 1 :(得分:3)

您应该free(ps)结尾deleteStack

temp d malloc的{​​{1}}指针会被char的结果覆盖,因此会被泄露。为什么需要分配单pop?只需将其初始化为char,或将其保持未初始化状态。

在生产代码中,您应该始终测试从NULLmalloc返回的值,并且永远不应该将realloc的结果分配给您尝试的内存的唯一指针重新分配。如果它重新发布realloc,你就泄露了它。

此外,在NULL中,您测试deleteStack,但仍然继续取消引用指针。