🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.lang.c.moderated
Article #2034

Re: 'Freeing' storage with realloc

#2034
From: Dan Pop
Date: Fri, 16 Feb 1996 15:30
62 lines
2550 bytes
In <4fvhro$e7u@solutions.solon.com> berndl@sidonius.fmi.uni-passau.de (Klaus Berndl) writes:


>Please look at the snipped of code:
>
>#include <stdio.h>
>
>main () {
>
>  char* buf = NULL;
>
>  buf = (char*)malloc(100);

I can't see any prototype or declaration for malloc in scope.  Without
the silly (char *) cast, the compiler itself would have complained, because
you can't assign an int to a char *.  Including <stdlib.h> is a _must_
when using malloc.

>  strcpy(buf, "Klaus Berndl");

I can't see any prototype or declaration for strcpy in scope.  This is
not a function returning an int, so it cannot be used without a declaration.
Including <string.h> is a must when using string handling routines.

>  printf("\n%s\n", buf);
>
>/* line 10 */  buf = (char*)realloc(buf, strlen(buf)+1);  /* line 10 */

The observation about malloc applies to realloc as well.

>  if (buf)
>    printf("\n%s\n", buf);
>  else
>    printf("\nshit!\n");

Returning something from main(), while not mandatory, is a very good idea.

>}
>
>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?

There is no (portable) way to tell.  There could be 1024 (or any other
arbitrary value) bytes allocated for buf for all you know.  Once you
attempt to access the storage behind byte 13, you invoke undefined
behaviour, so you can't draw any conclusion from the result.  If you
have resized buf to 13 bytes with realloc, you can access _only_ those
13 bytes (and hope that realloc has indeed freed the excess bytes).

A popular allocation algorithm rounds up the block sizes to the next
power of two, so, on some systems, the real size will be 16, but you are
still not allowed to access the extra 3 bytes.

Also note that the value of buf may change after the realloc call.

Dan
--
Dan Pop
CERN, CN Division
Email: danpop@mail.cern.ch 
Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
Technical Details
Message-ID: <4g27uk$qfv@solutions.solon.com>
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
References: <4fvhro$e7u@solutions.solon.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail
From: danpop@mail.cern.ch (Dan Pop)
Newsgroups: comp.lang.c.moderated
Subject: Re: 'Freeing' storage with realloc
Date: 16 Feb 1996 09:30:28 -0600
Organization: CERN European Lab for Particle Physics
Sender: clc@solutions.solon.com
Approved: clc@solutions.solon.com
Message-ID: <4g27uk$qfv@solutions.solon.com>
References: <4fvhro$e7u@solutions.solon.com>
NNTP-Posting-Host: solutions.solon.com
X-Newsreader: NN version 6.5.0 #7 (NOV)