我该如何摆脱函数返回一个指针? [英] How do I free a pointer returned from a function?

查看:145
本文介绍了我该如何摆脱函数返回一个指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&stdlib.h中GT;字符* F(无效){
  字符* X;
  X =的malloc(sizeof的(字符)* 4);
  的strcpy(X,ABC);
  回报(X);
}诠释主要(无效){
  字符*一个;
  一个= f()的;
  的printf(%S,一);
  自由(一);
  返回(0);
}

是否变量 X 中的功能已被释放?如果是这样,这怎么可能,当我需要退货吗?


解决方案

  

是否在函数变量x已被释放


是(有点儿,看我以后的评论)。到的malloc 每次调用要求免费以后的调用。否则,你有泄漏。但要记住;你是不是自由[和] X ,你是释放的x指的内存。

当您返回 X 的副本的 X 制成并返回给调用者。 X 宣布与自动存储时间。它是它是指必须被释放的存储器


  

如果这样怎么可能当我需要回去。


您设计放置在调用者的责任,以释放内存。你已经在主要的做到了这一点。当然,使用这种方法需要您记录的功能,使您的code用户知道他们正在接收地址这是动态分配的内存。

有一个更好的方法(IMO)是采取一个缓冲区作为输入参数。现在,它是很清楚谁是负责管理该内存(即主叫方)。也许我甚至不希望动态地分配它。采用这种设计是我的选择。

 无效F(的char * buf中,为size_t buf_size){
  函数strncpy(BUF,ABC,buf_size - 1);
  BUF [buf_size-1] ='\\ 0';
}


在一个侧面说明,你应该总是检查的malloc 的返回值。它可能会失败,在这种情况下,一个空指针将被返回。此外,的sizeof(char)的是有保障的标准是 1 ,这样你就可以删除该位,只是说的malloc(N)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* f(void) {
  char *x;
  x = malloc(sizeof(char) * 4);
  strcpy(x, "abc");
  return(x);
}

int main(void) {
  char *a;
  a = f();
  printf("%s", a);
  free(a);
  return(0);
}

Does the variable x in the function have to be freed? If so, how is that possible when I need to return it?

解决方案

Does the variable x in the function have to be freed?

Yes (kinda, see my later comment). Every call to malloc requires a later call to free. Otherwise, you have a leak. Remember though; you are not "free[ing] x", you are freeing the memory that x refers to.

When you return x a copy of the value (an address) of x is made and returned to the caller. x was declared with automatic storage duration. It is the memory it refers to that must be freed.

If so how is that possible when I need to return it.

Your design has placed the onus on the caller to free the memory. You have already done this in main. Of course, using this method requires that you document the function so that users of your code know that they are receiving an address to memory which was dynamically allocated.

A better approach (IMO) is to take a buffer as an input parameter. Now it is very clear who is responsible for managing this memory (i.e., the caller). Perhaps I don't even want to dynamically allocate it. With this design it is my choice.

void f(char *buf, size_t buf_size) {
  strncpy(buf, "abc", buf_size - 1);
  buf[buf_size-1] = '\0';
}


On a side note, you should always be checking the return value of malloc. It can fail, in which case a null pointer will be returned. Also, sizeof(char) is guaranteed to be 1 by the standard, so you can remove that bit and just say malloc(n).

这篇关于我该如何摆脱函数返回一个指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆