F
Franken Sense
In Dread Ink, the Grave Hand of Keith Thompson Did Inscribe:
There's two mallocs that could fail.
char *dupstr( char *pc )
{
char *pc2;
pc2 = malloc( strlen(pc) + 1 );
if (pc2 == NULL)
{
fputs("Malloc failed", stderr);
exit(EXIT_FAILURE);
}
if( pc2 )
{
strcpy( pc2, pc );
}
return pc2;
}
How do I unfurl this, so as to do likewise?
/* allocate memory for a node */
struct tnode *tree_alloc( void )
{
return malloc( sizeof( struct tnode ) );
}
I've been able to create trees big enough to make this a serious issue.
--
Frank
And by the way, a few months ago, I trademarked the word 'funny.' So when
Fox calls me 'unfunny,' they're violating my trademark. I am seriously
considering a countersuit.
~~ Al Franken, in response to Fox's copyright infringement lawsuit
[...]Franken Sense said:I assume the NULL happens when dupstr can't malloc, but I don't see what I
can do about it.
Yes, there are no really good responses to running out of memory. In
some cases, you might be able to abort just the current action and let
the program continue running, particularly in interactive programs.
In other cases, it might even make sense to fall back to a less
memory-intensive algorithm (though typically if you have such an
algorithm you'll just use it in the first place).
But at least you can abort the program with an error message. That's
almost always better than ignoring the error and trying to continue.
ptr = malloc(count * sizeof *ptr);
if (ptr == NULL) {
fputs("Malloc failed", stderr);
exit(EXIT_FAILURE);
}
There's two mallocs that could fail.
char *dupstr( char *pc )
{
char *pc2;
pc2 = malloc( strlen(pc) + 1 );
if (pc2 == NULL)
{
fputs("Malloc failed", stderr);
exit(EXIT_FAILURE);
}
if( pc2 )
{
strcpy( pc2, pc );
}
return pc2;
}
How do I unfurl this, so as to do likewise?
/* allocate memory for a node */
struct tnode *tree_alloc( void )
{
return malloc( sizeof( struct tnode ) );
}
I've been able to create trees big enough to make this a serious issue.
--
Frank
And by the way, a few months ago, I trademarked the word 'funny.' So when
Fox calls me 'unfunny,' they're violating my trademark. I am seriously
considering a countersuit.
~~ Al Franken, in response to Fox's copyright infringement lawsuit