c - 保留函数体中分配的内存

标签 c dynamic-memory-allocation

在其中一个程序中,我创建了一个函数,其参数是一个指针。该函数动态地向指针分配一些内存,并返回分配的内存的大小以及其他详细信息。但是,一旦函数执行,分配的内存就会被销毁。

如何保留函数外部对函数内部分配的内存的访问和数据完整性?

以下是阅读回复后修改的代码:

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/

相关文章:

c - 二进制搜索指针动态内存分配递归

c++ - unix 上可生成 xml 输出的 c++ 代码复杂性分析

可变等级堆栈中的 C 编程错误

c++ - 链表中修改的数据不会反射(reflect)在内存中

c++ - 当 QObject 被销毁时,Qt 可以安排将 QObject* 设置为 nullptr 吗?

c - 地址值与定义的结构长度没有精确差异。 [C]

c - 使用可变宏和函数时为 "Uninitialised value was created by a stack allocation"

C - 解码 base64 时的位移位

c - 如何使用 char var 字符串连接和调用系统

c - 在链表的第n个位置添加一个包含多位数字的节点