Sign in to follow this  

need help at working with files

This topic is 4041 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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[i]=(char *) malloc((strlen(buffer)+1)*sizeof(char)); strcpy(vp[i],buffer); vi[i]=0; }

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
thank you for the quick response. it works now. on the first line of the file is "n", of that i am sure. also i am sure the buffer is not overflowed.

Share this post


Link to post
Share on other sites

This topic is 4041 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this