Re: malloc()/realloc() - have I got this right?
- From: CBFalconer <cbfalconer@xxxxxxxxx>
- Date: Thu, 29 May 2008 17:37:02 -0400
Richard Heathfield wrote:
CBFalconer said:
Dave wrote:
I'm teaching myself C by working my way through Steve Summit's
tutorial (http://www.eskimo.com/~scs/cclass/cclass.html). In one
of the questions (assignment 6, exercise 7), you have to write a
function to read lines of arbitrary length from the command line,
using malloc() and realloc() to allocate the necessary memory to
hold the lines. I came up with this:
Instead of all that just get ggets.zip from:
<http://cbfalconer.home.att.net/download/ggets.zip>
Be aware, if you do so, that the above routine has what some people
consider to be serious design flaws. And of course you'll learn
more by writing your own than you will by pinching someone else's.
Here, without the documentation, .h file, test routines, etc. is
the actual (standard C) code for ggets.c. Instead of listening to
the mewling of people who don't like to see malloc called within a
routine, read the code, and make your own decision. ggets is a
macro in ggets.h that uses the FILE stdin.
#include <stdio.h>
#include <stdlib.h>
#include "ggets.h"
#define INITSIZE 112 /* power of 2 minus 16, helps malloc */
#define DELTASIZE (INITSIZE + 16)
enum {OK = 0, NOMEM};
int fggets(char* *ln, FILE *f)
{
int cursize, ch, ix;
char *buffer, *temp;
*ln = NULL; /* default */
if (NULL == (buffer = malloc(INITSIZE))) return NOMEM;
cursize = INITSIZE;
ix = 0;
while ((EOF != (ch = getc(f))) && ('\n' != ch)) {
if (ix >= (cursize - 1)) { /* extend buffer */
cursize += DELTASIZE;
if (NULL == (temp = realloc(buffer, (size_t)cursize))) {
/* ran out of memory, return partial line */
buffer[ix] = '\0';
*ln = buffer;
return NOMEM;
}
buffer = temp;
}
buffer[ix++] = ch;
}
if ((EOF == ch) && (0 == ix)) {
free(buffer);
return EOF;
}
buffer[ix] = '\0';
if (NULL == (temp = realloc(buffer, (size_t)ix + 1))) {
*ln = buffer; /* without reducing it */
}
else *ln = temp;
return OK;
} /* fggets */
/* End of ggets.c */
--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
.
- Follow-Ups:
- Re: malloc()/realloc() - have I got this right?
- From: rio
- Re: malloc()/realloc() - have I got this right?
- From: Richard Heathfield
- Re: malloc()/realloc() - have I got this right?
- References:
- malloc()/realloc() - have I got this right?
- From: Dave
- Re: malloc()/realloc() - have I got this right?
- From: CBFalconer
- Re: malloc()/realloc() - have I got this right?
- From: Richard Heathfield
- malloc()/realloc() - have I got this right?
- Prev by Date: Re: what is the output of this program?
- Next by Date: Re: in strspn(): what "spn" stands for?
- Previous by thread: Re: malloc()/realloc() - have I got this right?
- Next by thread: Re: malloc()/realloc() - have I got this right?
- Index(es):
Relevant Pages
|