473,508 Members | 2,342 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

in realloc(): warning: chunk is already free

I have the following code:

--- SNIP ---
// {{{ Code Fold: Includes and Defines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// }}} Code Fold: Includes and Defines
// {{{ Code Fold: Function Prototypes
void get_line( FILE *fp, char * line );
// }}} Code Fold: Function Prototypes
// {{{ Code Fold: main()
int main( int argc, char *argv[] )
{
unsigned int count = 0;
while ( !feof(stdin) )
{
char *line;
count++;
printf("> ");
get_line(stdin, line);
//printf("%s\n", *line);
}
printf("\nTotal lines: %u\n", count);
return 0;
}
// }}} Code Fold: main()
// {{{ Code Fold: get_line()
void get_line( FILE *fp, char * line )
{
char ch;
unsigned short iteration = 0;
while ( (ch = fgetc(fp)) != '\n' && !feof(fp))
{
// {{{ Code Fold: Allocate memory if this is the first
iteration
if ( iteration == 0 )
{
line = ( char * ) calloc( 2, sizeof(char));
if ( line == NULL )
{
puts("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
}
// }}} Code Fold: Allocate memory if this is the first
iteration
// {{{ Code Fold: Reallocate memory if this is the first
iteration
else
{
if ( realloc(line, (iteration + 2) * sizeof(char)) == NULL
)
{
puts("Memory reallocation failed\n");
exit(EXIT_FAILURE);
}
}
// }}} Code Fold: Reallocate memory if this is the first
iteration
line[ iteration ] = ch;
printf("line[%u] = '%c'\n", iteration, line[ iteration ] );
iteration++;
}
//printf("%s\n", line);
}
// }}} Code Fold: get_line()
--- SNIP ---

It compiles fine, no warnings of any kind, and starts fine. However,
any string longer than 15 characters breaks the program:

--- SNIP ---
01234567890123456789

line[0] = '0'
line[1] = '1'
line[2] = '2'
line[3] = '3'
line[4] = '4'
line[5] = '5'
line[6] = '6'
line[7] = '7'
line[8] = '8'
line[9] = '9'
line[10] = '0'
line[11] = '1'
line[12] = '2'
line[13] = '3'
line[14] = '4'
a.out in realloc(): warning: chunk is already free
Memory reallocation failed
--- SNIP ---
I'm extremely new to C in general, and searches on google only seem to
reveal people having this problem with existing programs. (i.e. ssh,
httpd, su, etc)

So any help is greatly appreciated!
Nov 13 '05 #1
1 3311

"Jeff" <go****@gurugeek.com> schrieb im Newsbeitrag
news:69**************************@posting.google.c om...
I have the following code:


[....]

Just a few corrections - I also reformatted your code and removed the
comments, which just made the code more difficult to read (others will point
out more, I guess :))
BTW
Please use "C" - style comments when posting, i this case the code still
compiles even if the comment lines wrap, and it will compile not only with a
C99 compiler, but also with C89
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void get_line( FILE *fp, char **line );
/*You should pass a _pointer_ to your char pointer in order to be able to
use the allocated memory in main()*/

int main( int argc, char *argv[] )
{
char *line = NULL;
unsigned int count = 0;

while ( !feof(stdin) )
{
count++;
printf("> ");
get_line(stdin, &line);
}
printf("\nTotal lines: %u\n", count);
/*Don't forget to:*/
free(line);
return EXIT_SUCCESS;
}
void get_line( FILE *fp, char **line )
{
int ch;
int iteration = 0;
char *tmp = NULL;

/*No need for an extra malloc(), realloc() with a NULL pointer as
argument 1 acts as a malloc()*/
while ( (ch = fgetc(fp)) != '\n' && !feof(fp))
{
/*Using a temporary pointer here makes sure, that the previously
allocated memory is still accessible if realloc fails*/
if ((tmp = realloc((*line), (iteration + 2) * sizeof(char))) == NULL)
{
/*if realloc() fails, (*line) still points to valid memory, so you
can take some sensible action here if you want*/
puts("Memory reallocation failed\n");
exit(EXIT_FAILURE);
}
else
{
*line = tmp;
}

(*line)[ iteration ] = (char)ch;
printf("line[%u] = '%c'\n", iteration, (*line)[ iteration ] );
iteration++;
}

}

HTH
Robert
Nov 13 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2076
by: DrBob | last post by:
gcc 3.3 on Mac OS X. I need to dynamically grow a buffer by concatinating raw binary data in chunks. How do I use 'new' to grow the buffer size as its contents grow? I know this can be done...
9
4041
by: Goh, Yong Kwang | last post by:
I'm currently doing a project that has a array that supposed to be determined only at runtime. Originally, the prototype I did as a proof of theory (or a quick hack) So one method is to create a...
4
4040
by: John | last post by:
I'm trying (struggling) to use realloc to grow a list of strings. The number of strings is not known (this is a subset of an assignment to write a recursive ls program... my BS was in EE, so I'm...
86
4061
by: Walter Roberson | last post by:
If realloc() finds it necessary to move the memory block, then does it free() the previously allocated block? The C89 standard has some reference to undefined behaviour if one realloc()'s memory...
8
1919
by: Jean-Claude Arbaut | last post by:
When you realloc for more size, it may be necessary to allocate a new block, copy memory and deallocate the old, for example if there is not enough free space after the original block (maybe the...
7
3755
by: Mischa | last post by:
Hello, I am trying to use realloc multiple times to extend an array of doubles but unfortunatly it keeps failing. I think I am mixing up the size to which the old memory block needs to be...
5
3853
by: lancer6238 | last post by:
Dear all, I'm trying to implement the Smith-Waterman algorithm for DNA sequence alignment. I'm aligning a 2040 bp query sequence against a 5040 bp sequence. I'll be trying to implement a parallel...
9
2310
by: Guillaume Dargaud | last post by:
Hello all, I have a 'good practice' question. Lately I've been using a lot of functions such as this: void Func(int Size, double *Array) { static double *Transformed=NULL;...
35
5623
by: Bill Cunningham | last post by:
My string.h headers declares two functions I have been using called memfrob and strfry. They are encryption types functions. My man pages say they are standard to linux c and gnu c. They sure...
0
7129
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7333
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7398
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
5637
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5057
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3208
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3194
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1566
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
428
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.