Article View: comp.lang.c.moderated
Article #2040Re: 'Freeing' storage with realloc
From: Daniel Popowich
Date: Sat, 17 Feb 1996 17:53
Date: Sat, 17 Feb 1996 17:53
61 lines
2619 bytes
2619 bytes
Klaus Berndl wrote:
>
> Please look at the snipped of code:
>
> #include <stdio.h>
>
> main () {
>
> char* buf = NULL;
>
> buf = (char*)malloc(100);
> strcpy(buf, "Klaus Berndl");
> printf("\n%s\n", buf);
>
> /* line 10 */ buf = (char*)realloc(buf, strlen(buf)+1); /* line 10 */
>
> if (buf)
> printf("\n%s\n", buf);
> else
> printf("\nshit!\n");
> }
>
> My questions are now: How much memory is allocated for 'buf' after
> executing line 10?! Does realloc 'freeing' the storage behind byte 13?
> Or are still 100 bytes allocated for buf?
>
Before answering your real question you should be aware of two errors in your
code: 1) you don't check the return value of malloc() and could end up with an ugly
segmentation fault in your strcpy(). 2) Should realloc() fail you will have a memory leak of
the storage pointed to by buf, having trashed that pointer. So I would rewrite like this:
char *buf, *tmp;
buf = malloc(100);
if (!buf)
ERROR_HANDLING;
strcpy(buf, "Klaus Berndl");
tmp = realloc(buf, strlen(buf) + 1);
if (!tmp)
ERROR_HANDLING;
else
buf = tmp;
As for your real question about realloc(): it may free the extra bytes, but then again,
maybe NOT. The first malloc() will return a space of at least 100 bytes. The realloc(),
only asking for 13 bytes, may do nothing and return buf (after determining that 87 bytes aint
worth the effort) or it might free the extra bytes. The standard does not specify a memory
management algorithm.
Don't make any assumptions about the underlying algorithms and know that your new space is
guaranteed to have only 13 bytes.
------------------------------------------------------------------------
Daniel Popowich popowich@cs.umass.edu (413) 545-9781
Applied Computing Systems Institute of Massachusetts, Inc. (ACSIOM)
Center for Intelligent Information Retrieval
Computer Science Department
University of Massachusetts, Amherst, MA 01003
-----------------------------------------------------------------------------
Technical Details
Message-ID:
<4g54n5$ah4@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4fvhro$e7u@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: Daniel Popowich <popowich@cs.umass.edu> Newsgroups: comp.lang.c.moderated Subject: Re: 'Freeing' storage with realloc Date: 17 Feb 1996 11:53:41 -0600 Organization: CS Dept., Umass-Amherst Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4g54n5$ah4@solutions.solon.com> References: <4fvhro$e7u@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com X-Mailer: Mozilla 2.0 (X11; I; SunOS 5.3 sun4m)