Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #43370

Re: freeing pointers that are created in a function

From James Kuyper <jameskuyper@verizon.net>
Newsgroups comp.lang.c
Subject Re: freeing pointers that are created in a function
Date 2014-04-22 17:42 -0400
Organization Self
Message-ID <5356E25C.6010805@verizon.net> (permalink)
References <33316bf9-6341-4a32-88a6-b2d4360e4f57@googlegroups.com>

Show all headers | View raw


On 04/22/2014 05:30 PM, G G wrote:
> let's say, in a function, malloc or calloc is called to allocate memory. the function returns a pointer to that allocated space.
> 
> question: once the function ends the only pointer to the allocated memory is that being assigned by the calling function. 
> 
> question: freeing the pointer being assigned to from the returning function is the only one that needs to be freed in order to keep from having a memory leak?

The only values that can safely be passed to free() are values that were
returned by previous calls to malloc(), calloc(), or realloc(); those
values, if not null, point to the start of the block of memory that was
allocated.

One such pointer value needs to be free()d.  If you don't have such a
pointer value saved somewhere, and cannot recreate such a pointer (for
instance, by subtracting from a pointer to some other part of the
allocated memory), you have a memory leak.

Any use of any pointer into the block of allocated memory has undefined
behavior after the call to free(), whether or not it's the one that you
passed to free(). In particular, it's undefined behavior to pass such
values to any function; free() itself is no exception to that rule.

Back to comp.lang.c | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

freeing pointers that are created in a function G G <gdotone@gmail.com> - 2014-04-22 14:30 -0700
  Re: freeing pointers that are created in a function James Kuyper <jameskuyper@verizon.net> - 2014-04-22 17:42 -0400
  Re: freeing pointers that are created in a function Ian Collins <ian-news@hotmail.com> - 2014-04-23 09:44 +1200
  Re: freeing pointers that are created in a function Kaz Kylheku <kaz@kylheku.com> - 2014-04-22 22:28 +0000
  Re: freeing pointers that are created in a function G G <gdotone@gmail.com> - 2014-04-22 22:35 -0700

csiph-web