need help at working with files
hello everybody. i am working with C.. and i have what i consider a strange problem. if i write the program using printf and scanf it runs, but if i change to using files (fprintf and fscanf) i have problems with dynamic memmory usage.
i have managed to isolate the problem to this portion of code. it fails at the line with the "breaks here". i really need help here cause i don't understand why it works when i do not use pointers and doesn't work when i also use files.
FILE *fin = fopen ("test.in", "r");
FILE *fout = fopen ("test.out", "w");
char **vp, *buffer=(char *) malloc(15);;
int i,n,vi[10],temp,k,j,p;
fscanf(fin,"%d", &n);
for(i=0; i<n; i++)
{
fscanf(fin,"%s", buffer);
/*breaks here*/ vp=(char *) malloc((strlen(buffer)+1)*sizeof(char));
strcpy(vp,buffer);
vi=0;
}
From the shown piece of code allocation of vp isn't obvious. I miss a line like
vp = (char**)malloc(n*sizeof(char*));
or the like after the fscanf(fin,"%d", &n) and before the loop.
However, are you sure that n is given in a textual representation in the file? Are you furthur sure that any line read by fscanf(fin,"%s", buffer) doesn't overflow the buffer?
vp = (char**)malloc(n*sizeof(char*));
or the like after the fscanf(fin,"%d", &n) and before the loop.
However, are you sure that n is given in a textual representation in the file? Are you furthur sure that any line read by fscanf(fin,"%s", buffer) doesn't overflow the buffer?
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement