gpt4 book ai didi

c - 内存分配 - 通过引用调用 String-Array-Parameter

转载 作者:太空宇宙 更新时间:2023-11-04 02:53:33 24 4
gpt4 key购买 nike

问题是如何在这个例子中正确分配/释放内存:

void test(char*** array, int* count) {

*array = malloc(sizeof(char*) * MAX_ARRAY);
while (...) {
(*array)[i] = (char*)malloc(strlen(fooString));
}
}

函数的调用:

char** array;
int count;
test(&array, &count);
// now free the memory - i think i have to?
for(i = 0; i < count; i++) {
free(array[i]); // <-- crash here
}
free(array);

看起来 array[0] 在测试函数内部的地址与外部地址不同。怎么会这样?看来我误解了某事,因为数组的地址在函数内外是相同的。

编辑:问题是我无法释放分配的内存(请参阅代码中的“此处崩溃”)。为什么?它将如何运作?

最佳答案

代替

void test(char*** array, int* count) {

*array = malloc(sizeof(char*) * MAX_ARRAY);
while (...) {
(*array)[i] = (char*)malloc(strlen(fooString));
}
}

void test(char*** array, int count) {

*array = malloc(sizeof(char*) * count); // number of pointers
for (int i = 0; i < count; ++i)
{
(*array)[i] = malloc(strlen(fooString));
}
}

尽管我不确定 fooString 是什么,因为您没有显示 decl/def。通常你会为\0

额外分配一个字节
(*array)[i] = malloc(strlen(fooString) + 1)

这似乎可行

#include <stdio.h>
#include <inttypes.h>
#include <malloc.h>
#include <string.h>

char fooString[256];

void test(char*** array, int count)
{
int i = 0;
*array = malloc(sizeof(char*) * count);
for (i = 0; i < count; ++i)
{
(*array)[i] = malloc(strlen(fooString)+1);
}
}

int main()
{
char** array = NULL;
int count = 100;
int i = 0;
test(&array, count);


for(i = 0; i < count;++i)
{
free(array[i]);
}
free(array);
return 0;
}

关于c - 内存分配 - 通过引用调用 String-Array-Parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19682790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com