Reputation: 3
I'm new here and don't speak very well english. I've a question concerning my code (in C).
What the code should do:
There exists a file named "g.txt", that should be opened. Then it reads it line by line and copies each line in a buffer (zpuffer[200]
), after that the content of the buffer should be copied with strcpy to **Dfile
. **Dfile
points to a char*
, its space was first allocated with malloc
. If **Dfile
hasn't enough space for saving, the code executes realloc
, that shoud make more free space.
The first time realloc
have been called, I actually got more space! But the second time, it didn't work; the OS, Ubuntu, says (in German): "Bus-Zugriffsfehler (Speicherabzug geschrieben)". English: "Bus access error (written dump)"
Here is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define OBJS 10 //new Lines a one time for **Dfile
int main(void){
FILE *datei;
datei=fopen("g.txt", "r");
if (datei == NULL){
fprintf(stderr, "\nFEHLER\n");
return 1;
}
char zpuffer[200]; //buffer
char **Dfile; //save content of g.txt line by line, every line has its own index
int zeilen = 0; //the actual amount of lines
int speicher = 0; //total indices in **Dfile
Dfile = (char**)malloc(sizeof(char**)*(speicher + OBJS));
speicher += OBJS;
while (fgets(zpuffer, 199, datei) != NULL){
if (speicher <= zeilen){//speicher <= zeilen --> allocate memory
Dfile = (char**)realloc(*Dfile, sizeof(char**)*(speicher + OBJS)); //!!ERROR!! but just the second time!!
if (Dfile == NULL){
fprintf(stderr, "\nFEHLER Alloc\n");
return 1;
}
speicher += OBJS;
}
Dfile[zeilen]=malloc(strlen(zpuffer)+1);
strcpy(Dfile[zeilen++], zpuffer);
printf("%s", Dfile[zeilen - 1]);
}
return 0;
}
May someone help me, please??
Upvotes: 0
Views: 544
Reputation: 473
You pass *Dfile
to realloc()
.
Did you meant to pass Dfile
instead?
Upvotes: 2