HEAP CORRUPTION检测到C中的内存泄漏

时间:2018-02-21 21:54:25

标签: c

我得到了错误,说

  

调试断言失败并检测到热损坏

就像我的程序中的一切都运行良好但我得到了这个错误。这里的内存泄漏在哪里?我必须在main中释放该内存,因为我的函数需要返回指针。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *dynamic_reader(unsigned int n) {

    /*making new array and checking if allocation succeeded*/
    int *mem;
    mem = malloc(n * sizeof(int));
    if (!mem) {
        printf("Memory allocation failed\n");
        exit(-1);
    }

    /*letting the user to input the values for the array*/
    int i = 0;
    while (i < n) {
        scanf("\n%d", &mem[i]);
        i++;
    }

    /*printing the array just to make sure everything is good*/
    for (int j = 0; j < n; j++) {
        printf("%d  ", mem[j]);
    }

    return mem;
}
int *insert_into_array(int *arr, unsigned int num, int newval) {

    /*making new bigger array*/
    int *newarr = realloc(arr, (num + 1) * sizeof(int));

    /*adding the integer to this new array */
    newarr[num] = newval;
    printf("\n");

    /*printing to make sure everything is correct*/
    for (int j = 0; j < num + 1; j++) {
        printf("%d  ", newarr[j]);
    }
    return newarr;
}
int main(void) {
    /*In dynamic_reader function I need to make an array which size is given as a parameter*/
    /*In this case I choosed 3*/
    int *arr = dynamic_reader(3);
    int num = 3;
    /*In insert_into_array function I need to add one integer to this array I made in dynamic_reader*/
    /*The parameters are the array, the number of elements in the array already done and the integer I want to add*/
    int *c = insert_into_array(arr, num, 9);

    /*I free the memory here because I need to return the pointers of these arrays in the function so it cant be done there*/
    free(arr);
    free(c);
}

3 个答案:

答案 0 :(得分:3)

你是双重释放你的记忆。查看realloc的文档。 Realloc将1)扩展传递的缓冲区或2)将分配新的缓冲区,复制数据,并释放原始缓冲区。当你这样做时:

free(arr);
free(c);

您可以双重释放曾经由realloc释放或已被第一个free(arr)释放的值

此外,您应该检查realloc是否失败(返回NULL),如果是,请正确处理案例。

答案 1 :(得分:1)

首先,您malloc一个数组,您将其作为arr返回主函数。然后在另一个函数中,realloc其中arr是realloc的参数,但是其他一些指针存储结果。根据realloc中发生的情况,您要么arrnewarr指向同一位置,要么newarr指向有效位置,arr指向无效位置已释放的位置。无论哪种方式,最终释放它们都是一个问题。

答案 2 :(得分:1)

无需 import Header from './components/Header' free(arr)时就会照顾到它。 realloc()返回的指针将指向包含原始内存的内存,或者在将其内容复制到新的更大内存块后释放旧内存。