Jump to content
  • Advertisement
Sign in to follow this  
white

need help at working with files

This topic is 4252 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=(char *) malloc((strlen(buffer)+1)*sizeof(char)); strcpy(vp,buffer); vi=0; }

Share this post


Link to post
Share on other sites
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!