-2

So i have a function that allocates a part of memory, then fills it with data and then returns it. i also want to free this allocated memory but if i free it before return it will return null, also if i try to free after return, since function ends when it see return, it won't free the memo. So i asked a couple friends one of them said there is a syntax that returns the data and free it at the same time. Tho i couldn't find anything about it in the net and i need help.

i tried some braindead attemptions like return (free(x)); and return ((x)free); ??? but obviusly they didn't work.

  • 3
    You can't. If you free the memory, its no longer valid to reference it. If you want your ownership model to be such that every component that allocates the memory is responsible for freeing it, then you will have to require that the caller pass the memory in to your function. But it is fairly typical to let the caller free the memory. eg, consider `x = strdup(); free(x);` In that case `strdup` allocates memory, and the caller free's it. – William Pursell Jul 20 '23 at 03:11
  • 3
    @Alper Tangil. "i have a function that allocates a part of memory ...." -->post the code rather than only describe it. – chux - Reinstate Monica Jul 20 '23 at 04:39
  • Your friend may have been referring to [smart pointers](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one). Those are available in C++, but not in C. – user3386109 Jul 20 '23 at 04:43
  • @Alper Tangil. "also if i try to free after return, since function ends when it see return, it won't free the memo." is amiss. True that the function won't free the memory, yet that is OK. The calling code can free the memory. Why do you not want the calling code to free the memory? – chux - Reinstate Monica Jul 20 '23 at 12:47

2 Answers2

3

It's undefined behaviour to access memory that has been freed. As such, it would be useless to return a pointer to memory you freed. You'll just to leave it to the caller to free it after it's done with it.

ikegami
  • 367,544
  • 15
  • 269
  • 518
1

You could pass a pointer to the function, allocate the memory and write the needed data into it. After the function returns, the pointer to the data will be available in your caller function same as before with the memory allocated and the data stored. You can free the memory there after you did what you wanted with the data.