首页 > realloc:pointer being realloc'd was not allocated

realloc:pointer being realloc'd was not allocated

在做一个leetcode的题,遇到了一个奇怪的问题,调用realloc为array扩容,报错

malloc: error for object 0x7f7fc0404bf0: pointer being realloc'd was not allocated

在下面的代码中,第一次realloc的时候是ok的,第二次调用到realloc的时候就会报错了

请问如何修改可以解决,以及为什么

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

void generate(int left, int right, int currentLen, char* str, char** result, int* resultCount, int* resultCapacity) {
    if (right < left) {
        return;
    }
    if (left == 0 && right == 0) {
        char* temp = malloc(sizeof(char) * (currentLen + 1));
        temp = strcpy(temp, str);
        result[*resultCount] = temp;
        (*resultCount)++;
    }
    if (*resultCount >= *resultCapacity) {
        *resultCapacity = (*resultCapacity) * 2;
        char** temp = realloc(result, sizeof(char*) * (*resultCapacity));
        result = temp;
    }
    if (left > 0)  {
        str[currentLen] = '(';
        str[currentLen + 1] = '\0';
        generate(left - 1, right, currentLen + 1, str, result, resultCount, resultCapacity);
    }
    if (right > 0) {
        str[currentLen] = ')';
        str[currentLen + 1] = '\0';
        generate(left, right - 1, currentLen + 1, str, result, resultCount, resultCapacity);
    }
}

char** generateParenthesis(int n, int* returnSize) {
    if (n < 1) {
        return NULL;
    }
    int* resultCount = malloc(sizeof(int));
    int* resultCapacity = malloc(sizeof(int));
    (*resultCount) = 0;
    (*resultCapacity) = n;
    char** result = malloc(sizeof(char*) * (*resultCapacity));
    char* str = malloc(sizeof(char) * (n * 2 + 1));
    generate(n, n, 0, str, result, resultCount, resultCapacity);
    *returnSize = *resultCount;
    return result;
}

int main(int argc, char const *argv[]) {
    int* returnSize = malloc(sizeof(int));
    char** result = generateParenthesis(5, returnSize);
    for (int i = 0; i < *returnSize; ++i) {
        printf("%s\n", result[i]);
    }
    return 0;
}

我觉得问题出现 在你的 generate() 递归中; 你在 下一级的 generate()调用里 把result指向 的 内存区给 realloc了; 你把 realloc返回值 写给 result是没有用的, result是一个形参, 不会影响到 上一级调用的 实参.

就是说, 你需要 把result参数定为 一个 三级指针; 在每次realloc之后, 把新的 地址写回 给上一级. 嫌麻烦的话, 把result定义为全局变量吧.

void generate(int left, int right, int currentLen, char* str, char*** result, int* resultCount, int* resultCapacity) {
    ...
    if (*resultCount >= *resultCapacity) {
        *resultCapacity = (*resultCapacity) * 2;
        char** temp = realloc(*result, sizeof(char*) * (*resultCapacity));
        *result = temp;
    }
    ...
}

char** generateParenthesis(int n, int* returnSize) {
    ...
    char** result = malloc(sizeof(char*) * (*resultCapacity));
    ...
    generate(n, n, 0, str, &result, resultCount, resultCapacity);
    ...
}
【热门文章】
【热门文章】