munmap_chunck(): c 中的无效指针

munmap_chunck(): invalid pointer in c

我写了一个程序来做一些数据分析,这个数据存储在一个名为 P 的全局结构中。我在一个函数中为这个结构分配内存,然后,因为我需要它整个程序,直到 main 的最后才调用 free。在 main 中不调用 Malloc,因为数组的大小是从文件中获取的,所以我认为读入文件并在那里分配内存比在 main 中完成所有操作更有意义。

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

typedef struct DATA
{
    /* variables*/
} DATA;

DATA *P;
void function1(void);

int main(int argc, char **argv)
{
    function1();
    /*do some stuff*/
    free(P);
    return 0;
}

void function1(void)
{
    if(!(P = (DATA *)malloc(nums * sizeof(DATA))))
    {
        printf("Error!\n");
        exit(EXIT_FAILURE);
    }
    /*do stuff*/
}

本质上,当我 运行 我的代码时,我收到错误:munmap_chunck():无效指针。我读了一些书,似乎与 free 功能有关。我还读到 malloc 和 free 应该在同一个函数中调用。如果是这种情况,那么我的问题是:既然 P 是一个全局变量,为什么为这个特定变量调用哪个函数 malloc 和 free 很重要?事实上,如果问题不是由不同函数调用 malloc 和 free 引起的,那么有人对它可能是什么有任何建议吗?非常感谢你!

这是一个常见问题,当您提供 free 一个不指向已分配内存块开头的指针时会发生这种情况。例如,代码

int* something = malloc(sizeof(int)); // Allocate space for 1 int
...
free(something);

将正常工作,因为您向 free 提供 malloc 返回的原始指针。但是,如果您这样做:

int* something = malloc(sizeof(int) * 5); // Allocate space for 5 ints
...
something += sizeof(int); // Shift the allocated memory by 1 int
...
free(something);

然后 free 已经提供了一个指向已分配内存块中间某处的指针。这意味着 free 根本不知道块从哪里开始或结束,因此会抛出错误。这可以通过将原始指针值存储在另一个指针中来解决:

int* something = malloc(sizeof(int) * 5);
int* another_something = something; // `another_something` contains the same pointer value as `something`
...
something += sizeof(int); // `something` changes, `another_something` doesn't
...
free(another_something); // Free the original pointer

所以,在你的情况下,是这样的:

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

typedef struct DATA
{
    /* variables*/
} DATA;

/* Declare another DATA*, P1 */
DATA *P, *P1;
void function1(void);

int main(int argc, char **argv)
{
    function1();
    /*do some stuff*/

    /* Free the original pointer, in P1 */
    free(P1);
    return 0;
}

void function1(void)
{
    if(!(P = (DATA *)malloc(nums * sizeof(DATA))))
    {
        printf("Error!\n");
        exit(EXIT_FAILURE);
    }

    /* Store the original value of `P` in P1 */
    P1 = P;

    /*do stuff*/
}

最后,请修正您的命名约定。 Pfunction1 是糟糕的名字。