free():在 tcache 2 中检测到双重释放已中止

问题描述 投票:0回答:1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void ffree(char **pp)
{
        if (!pp)
        return;

    char **a = pp;

      while (*pp) {
        free(*pp);  // Free the memory pointed to by pp
        pp++;       // Move to the next pointer
    }

    free(a); // Finally, free the memory for the array of pointers
}

int main() {
    char *str1 = strdup("Hello");
    char *str2 = strdup("World");
    
    char *arr[] = {str1, str2};

    ffree(arr);

    return 0;
}

在上面的简单代码片段中,我编写了自己的字符串数组释放函数,其中我释放了指向字符串数组的指针

我的代码有问题吗?

c pointers dynamic-memory-allocation free
1个回答
0
投票

char *arr[] = {str1, str2};
这里数组末尾没有 NULL 指针哨兵值。

因此这没有任何意义:

  while (*pp) {
    free(*pp);  // Free the memory pointed to by pp
    pp++;       // Move to the next pointer
© www.soinside.com 2019 - 2024. All rights reserved.