Trying to figure out how to dynamically re-allocate strings while concatenating

  • Thread starter Shriramana Sharma
  • Start date
B

Ben Bacarisse

Keith Thompson said:
Oops, what I *meant* was

buf = realloc(buf, 200);


The point I was making upthread was specifically about realloc() (and of
course I messed that up by typoing "malloc" in place of "realloc").

Assigning the result of realloc() to the pointer object given as the
first argument is considered a bad idea because, if the realloc() call
fails and returns a null pointer, you've lost your only pointer to the
original buffer. My point was merely that losing that pointer is bad
only if you would have made use of it. If your response to an realloc()
failure is going to be to abort the program anyway, then you might as
well write

buf = realloc(buf, new_size);

I did *not* mean to suggest omitting the check for a null pointer. If
an allocation call fails, you want to deal with it immediately -- even
if you're just going to abort the program.

Yes, I got that that was your point, and I had nothing to say about it
(because I agree). That's why I replied to Jens's post and not yours.
 
P

Phil Carmody

The result of an attempt should always be checked according
to me. The »free« below is not really required for this
small program, but would be helpful in many cases, where the
code is repeatedly executed in a program.

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

char * strapp( char * * const a, char const * const b )
{ *a = realloc( *a, 1 + strlen( *a )+ strlen( b ));
if( *a )strcat( *a, b );

Else? The memory *a used to point to will, however, still be
allocated, but you no longer have a reference to it. That's a leak.
return *a; }

The caller already knows what *a is, you don't need to tell
him twice. (This is a redundancy in some of the standard
library too, in particular in the str functions.)

Phil
--
I'd argue that there is much evidence for the existence of a God.
Pics or it didn't happen.
-- Tom (/. uid 822)
 
S

Stefan Ram

Phil Carmody said:
(e-mail address removed)-berlin.de (Stefan Ram) writes:
(...)
Else? The memory *a used to point to will, however, still be
allocated, but you no longer have a reference to it. That's a leak.

Yes. (Someone already said this before in this thread.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,079
Messages
2,570,573
Members
47,205
Latest member
ElwoodDurh

Latest Threads

Top