2

i am just doing a program in C, which has to read different files in csv-format. Every file consists of two lines. The first line describes what topics are saved, while the second lines contains the data of the topics. Every file has 6 columns. The data are information like dates, source and category. I actually wrote a program that get the path and gives the content in one dynamical char array back, but there is always a Debug Assertion Error that crashes it all the time. My Code is:

char* readfile(char csvpath[]) {
FILE *csv;
int c;
int countcontent = 100;                 //counter for the length of the content array
int counter = 0;                    //counter  of the amount of the inserted chars
char *temp;                     //temp = buffer
char *content = (char*)calloc(100,sizeof(char));    //content of the file
csv = fopen(csvpath,"r");
while(c = fgetc(csv) != EOF) {              //while file isnt at the end
    if(countcontent <= counter) {
        realloc(content,100*sizeof(char));
        countcontent += 100;
    }
    temp = (char*)calloc(20,sizeof(char));
    fgets(temp,20,csv);
    content = concat(content,temp);         //concat is my own function and add the 2. string behind the 1.
    counter+= 20;
}
fclose(csv);
return content;}

Assert Screenshot Actually i ignore that there are two different lines, cause i want to delete the first one at the end anyway, because no data is saved there. But can you help me to find the solution for this error?

manuell
  • 7,528
  • 5
  • 31
  • 58
LAN
  • 21
  • 1

1 Answers1

1

Your problem is this line

realloc(content,100*sizeof(char));

The realloc function returns a pointer to the reallocated memory. Think about what would happen if the realloc call can't just resize the already allocated chunk, and has to actually allocate a completely new chunk of memory, because it can't automatically update the pointer you pass to it.

Another problem with that statement is that it doesn't matter how much more memory you need, you will always allocate 100 bytes. The size argument you provide to realloc is the new size.

Oh, and remember that realloc can fail, and return a NULL pointer. If you don't want to loose your original pointer, you need to have a temporary variable to store the returned pointer, and check it for NULL.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • You mean i have to use content = realloc(content,100*sizeof(char));? Actually when i use debugger my program don´t come so far, it stops already in the while instruction. – LAN Jan 23 '15 at 09:20
  • @LAN Read my whole answer, and follow the links to the `realloc` reference and read that as well. – Some programmer dude Jan 23 '15 at 09:26
  • @LAN As for the crash in `fgetc` (most likely) it probably because the `fopen` call failed and gave you a `NULL` pointer. For ***all*** functions that return a value should ***always*** check the value returned for errors. – Some programmer dude Jan 23 '15 at 09:27