【问题标题】:How to free the pointer to int, which then becomes the pointer to the result of the function?如何释放指向 int 的指针,然后它成为指向函数结果的指针?
【发布时间】:2014-03-20 21:45:15
【问题描述】:

我有一个指向 int 的指针:

   int* convex = (int*)malloc(sizeof(int));
   if(convex == NULL) {
       free(convex);
       return 0;
   }

然后我会这样做:

convex = check_figure(x_points, y_points);

函数已声明:

int* check_figure(float* x_points[], float* y_points[]);

然后我做:

free(convex);

for( i = 0; i < n+1; i++) {
    free(x_points[i]);
    free(y_points[i]);
}

free(x_points);
free(y_points);

为什么 valgrind 说我没有为 variable:convex 释放内存?


数组没问题,因为我喜欢这样:

x_points = (float**)malloc(sizeof(float*) * (n+1));


y_points = (float**)malloc(sizeof(float*) * (n+1));

【问题讨论】:

  • 为什么在您的第一个代码示例中,您在 NULL 指针上调用 free?这在技术上是合法,但它是非常奇怪的事情,所以你能解释一下你为什么这样做吗?
  • 这些sn-ps不是很清楚;发布完整的工作计划。

标签: c pointers


【解决方案1】:

你分配内存

int* convex = (int*)malloc(sizeof(int));

然后你覆盖指针

convex = check_figure(x_points, y_points);

第一个 malloc 永远不会被释放。根据您覆盖第一个指针的内容,您可能会遇到其他内存错误。

正如 cmets 中所指出的,如果你想从函数返回一个值,你可以通过解引用指针将它存储在第一个分配的 int 中:

*convex = check_figure(x_points, y_points);

【讨论】:

  • 一般来说:我需要从函数中返回指向 int 的指针......做得正确吗?我现在能做什么?谢谢你的回答
  • convex = check_figure(x_points, y_points); 行不会将指向的数据从返回值复制到您 malloc'd 的内存中。它使convex 指向返回值所指向的数据,而不是指向 malloc 的内存。您可能需要存储返回的指针并将正确数量的字节从中复制到 malloc'd 区域。
  • 从函数返回指针没有问题,如果你不需要第一次分配,就不要这样做。如果您可以发布 check_figure 的实现,那将有助于提供更好的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 2017-09-03
相关资源
最近更新 更多