malloc()/realloc() - have I got this right?
- From: Dave <dave@xxxxxxxxxxxxxx>
- Date: Tue, 27 May 2008 17:56:55 -0500
Hello,
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:
char *getline(char *line)
{
int line_len = 0;
int max_len = 32; /* initial guess */
char *start; /* pointer to start of string is the return value */
char *count;
int c;
line = malloc(max_len * sizeof(char));
if (line == NULL)
{
printf("Out of memory.\n");
exit(1);
}
start = line;
count = line;
while ((c = getchar()) != EOF)
{
if (c == '\n')
break;
if (line_len == max_len - 1)
{
max_len *= 2;
line = realloc(line, max_len * sizeof(char));
if (line == NULL)
{
printf("Out of memory.\n");
exit(1);
}
}
*count++ = c;
line_len++;
}
*count = '\0';
return start;
}
And I'm using this to test it:
int main()
{
char *line;
int i;
for (i = 0; i < 5; i++)
{
line = getline(line);
printf("%s\n%d\n", line, strlen(line));
}
return 0;
}
On Linux it seems to work with lines of any length. On Windows (using the
MinGW compiler) it fails if the line is longer than 1024 characters (just
prints out a few random characters and reports the length as 0). I'm
hoping someone can tell me if I've got this function basically right -
have I introduced some bug which is causing the crash, or is it a Windows
thing that I don't need to concern myself with?
Also, is it better in principle to make more calls to realloc() to ensure
that you get exactly the memory you need and no more, or to make fewer
calls and just malloc() more than you think you'll need at the beginning?
Thanks for any help.
.
- Follow-Ups:
- Re: malloc()/realloc() - have I got this right?
- From: CBFalconer
- Re: malloc()/realloc() - have I got this right?
- From: Flash Gordon
- Re: malloc()/realloc() - have I got this right?
- From: Jens Thoms Toerring
- Re: malloc()/realloc() - have I got this right?
- From: Walter Roberson
- Re: malloc()/realloc() - have I got this right?
- Prev by Date: Re: Very Small C Compiler which can generate DLL files?
- Next by Date: Re: malloc()/realloc() - have I got this right?
- Previous by thread: preprocessing statements
- Next by thread: Re: malloc()/realloc() - have I got this right?
- Index(es):
Relevant Pages
|