# Problems with calloc() and free() in C Programm



## dummy666 (Nov 24, 2008)

Hi!
I'm writing a programm in C which is requesting the absolute Path of a file from the user.
Opens the file,requests keywords and the filters the file line by line.
To resist keyboard overflows I'm working with calloc(),getc(),and pointers().
This Method can take an arbitray number of inputs and still executes normaly(as long as Ram isn't exceeded, as far as I can tell).
So I don't think the Problem can be found there.
The following Code shows the filter()-Function, which takes a Pointer of type FILE* and a Pointer-Array,holding Strings,beeing the keywords.
It really freaks me out not finding the cause for this error.

Errormessage: free(): invalid size: 0x099d0408

Last but not least: does anyone know a IRC channel which is discussing the C programming language,in case I need some"realtimesupport" really badly?
Only found deserted ones and IRC's handeling C++-issues only.
sincerly
dummy

In case I forgot to rename some variables:
datei := file
suchkriterien := searchkriterien
suchkriterienbackup := searchkriterienbackup


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

char* filter(FILE *file,char** searchkriterien)
{
int size = 10;
char character= ' ';
char* working = (char*) calloc(size,sizeof(char));
char*backup,*tmp;
char *backup2,*result;
char** searchkriterienbackup = searchkriterien;
int counter = 0;
backup2 = result = (char*) calloc(size,sizeof(char));
tmp = backup = working;

do
{
do
{
character = fgetc(file);
if(counter == size -2)
{
tmp = calloc(size*2,sizeof(char));
tmp = memcpy((void*)tmp,(const char*) backup,counter);
free(backup);
backup = working = tmp;
working +=size-2;
size *=2;
}
counter++;
if(!feof(file))
*(working)++ = character;//evtl ist hier die syntax falsch *(result)++ <=>*result++
else
*(working)++ = '\n';


}while(character != '\n'||feof(file));

while(*(searchkriterien) != NULL)
{
if(NULL!= strstr(backup,*(searchkriterien)++))
{
backup2 = (char*) calloc(strlen(backup)+strlen(backup2),sizeof(char));
backup2 = memcpy((void*)backup2,(const char*)result,strlen(result));
result = backup2;
strcat(result,backup);
break;
}
}
free(backup);
searchkriterien = searchkriterienbackup;
size = 10;
counter = 0;
tmp =(char*) calloc(size,sizeof(char));
backup = working = tmp;

if(feof(file))
break;

}while(1);
free(backup);

return backup2;
}


----------

