在其中一个程序中,我创建了一个函数,其参数是一个指针。该函数动态地向指针分配一些内存,并返回分配的内存的大小以及其他详细信息。但是,一旦函数执行,分配的内存就会被销毁。
如何保留函数外部对函数内部分配的内存的访问和数据完整性?
以下是阅读回复后修改的代码:
void initialize(int **arr)
{
int i = 0;
*arr = malloc(sizeof(int) * 10);
for (; i < 10; ++i)
*arr[i] = i + 1;
for (i = 0; i < 10; ++i)
printf("\n%d", *arr[i]);
}
int main()
{
int i = 0;
int *arr;
initialize(&arr);
for (; i < 10; ++i)
printf("\n%d", arr[i]);
return 0;
}
但是当我运行它时,它说“rr.exe已停止工作”;虽然编译成功了。没有打印任何内容,甚至函数中的 printf 也没有打印任何内容。
最佳答案
不要对动态分配接收到的指针调用free()
,而是将其从函数返回到调用进程。
示例:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
/* give_me_memory(void ** ppv, size_t n) allocates n bytes to *ppv. */
/* The function returns 0 on success or -1 on error. On error errno is set accordingly. */
int give_me_memory(void ** ppv, size_t n)
{
if (NULL == ppv)
{
errno = EINVAL; /* Bad input detected. */
return -1;
}
*ppv = malloc(n);
if (NULL == *ppv)
{
return -1; /* malloc() failed. */
}
return 0; /* Getting here mean: success */
}
int main(void)
{
void * pv = NULL;
if (-1 == give_me_memory(&pv, 42))
{
perror("give_me_memory() failed");
return 1;
}
/* Do something with the 42 bytes of memory. */
free(pv);
return 0;
}
关于c - 保留函数体中分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586319/