944,117 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Marked Solved
  • Views: 2266
  • C RSS
Jan 16th, 2007
0

problem with freeing memory

Expand Post »
I'm almost finished with this program but the problem I'm having is with freeing the memory I allocated. Particularly in the area where I have pointers to strings.

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. /////////////// user defined data /////////////////////
  6. struct State
  7. {
  8. char * name; // state name
  9. int year; // year of entry into the union
  10. char * cap; // state capital
  11. int popRank; // population ranking
  12. };
  13.  
  14. struct Database
  15. {
  16. struct State * list; // array of states
  17. int count; // total count of states
  18. char * filename; // input filename
  19. };
  20.  
  21.  
  22. /////////////// function prototypes ////////////////////
  23. struct Database * initDatabase (char * filename);
  24. void deleteDatabase (struct Database * db);
  25. void fillDatabase (struct Database * db);
  26. void insertDatabase (struct Database* db, int index, struct State * state);
  27. void printDatabase (struct Database * db);
  28.  
  29. int initState (struct State * state, char * name, int year, char * cap, int popRank);
  30. void deleteState (struct State * state);
  31. void copyState (struct State * from, struct State * to);
  32. void printState (struct State * state);
  33.  
  34.  
  35.  
  36. ////////////////////////// program start ///////////////////////////////////////
  37. int main(void)
  38. {
  39. struct Database * db;
  40.  
  41. if (db = initDatabase("states.txt")) // allocate memory for Database struct,
  42. // then initialize fields of Database struct
  43. {
  44. fillDatabase(db); // read from file
  45. printDatabase(db); // print data
  46. deleteDatabase(db); // free memory in Database struct
  47. free(db); // free Database struct itself
  48.  
  49. return 0;
  50. }
  51. else // not successful
  52. {
  53. return 1;
  54. }
  55. }
  56.  
  57. ////////////////////// Database functions ////////////////////////////////
  58.  
  59. //initDatabase - allocates memory for Database struct and initializes
  60. // each field
  61. //input: input filename
  62. //return: pointer to Database struct if success
  63. // NULL if fail
  64. struct Database * initDatabase (char * filename)
  65. {
  66. FILE * fpIn;
  67. struct Database * db;
  68. struct State * states;
  69. char * string;
  70.  
  71. // open input file and check for open success
  72. if ( ( fpIn = fopen( filename, "r" ) ) )
  73. {
  74. // allocate memory for Database struct and check for success
  75. if ( db = ( struct Database * )malloc( sizeof( struct Database ) ) )
  76. {
  77. // allocate memory for filename field and initializes with filename
  78. if ( string = ( char * )malloc( sizeof( char ) * strlen( filename ) ) )
  79. {
  80. strcpy( string, filename );
  81. db->filename = string;
  82. }
  83. else
  84. {
  85. printf("Not enough memory!\n");
  86. exit(0);
  87. }
  88.  
  89. // initialize count field to 50
  90. db->count = 50;
  91.  
  92. // initialize list field by allocating memory for array of 50 states
  93. // and check for success
  94. if ( states = ( struct State * )malloc( sizeof( struct State ) * 50 ) )
  95. {
  96. db->list = states;
  97. }
  98. else
  99. {
  100. printf("Not enough memory!\n");
  101. exit(0);
  102. }
  103. }
  104.  
  105. }
  106. else
  107. {
  108. printf("Error with file!\n");
  109. exit(0);
  110. }
  111.  
  112. // close input file
  113. fclose( fpIn );
  114.  
  115. return db;
  116. }
  117.  
  118. //deleteDatabase - frees allocated memory inside a Database struct
  119. //input: pointer to Database struct
  120. //return: nothing
  121. void deleteDatabase (struct Database * db)
  122. {
  123. while ( db->list )
  124. {
  125. deleteState( db->list );
  126. db->list++;
  127. }
  128. }
  129.  
  130. //fillDatabase - reads info from file and stores in array of State structs
  131. //input: pointer to Database struct
  132. //return: nothing
  133. void fillDatabase (struct Database * db)
  134. {
  135. struct State tempState; // temp State struct to store data from file
  136. char name[80]; // temp variables
  137. int year; // to store
  138. char cap[80]; // input data
  139. int popRank; // from file
  140. int index = 0; // index into array of State structs
  141.  
  142. FILE *fpIn;
  143. int cnt;
  144.  
  145. // open file from filename field of db
  146. // don't need to check for file open success because initDatabase already checked
  147. fpIn = fopen( db->filename, "r" );
  148.  
  149. // loop through all the states
  150. for ( cnt = 0; cnt < db->count; cnt++ )
  151. {
  152. // read and parse one line of file into 4 input data fields
  153. if ( fscanf( fpIn, "%[^,], %d, %[^,], %d", name, &year, cap, &popRank ) == 4 )
  154. {
  155. // if tempState is created successfully from the 4 input data
  156. if ( initState (&tempState, name, year, cap, popRank) )
  157. { // then copy tempState data into array of states at the current index
  158. insertDatabase (db, index, &tempState);
  159. }
  160. index++;
  161. }
  162. else
  163. {
  164. printf("Error reading file!\n");
  165. exit(0);
  166. }
  167. }
  168.  
  169. // close file
  170. fclose( fpIn );
  171. }
  172.  
  173. //insertDatabase - copy state data from tempState into appropriate place in array
  174. //input: pointer to Database struct
  175. // current index in array
  176. // pointer to tempState containing state data
  177. //return: nothing
  178. void insertDatabase (struct Database * db, int index, struct State * state)
  179. {
  180. // set pCurrent to location to be inserted in array
  181. struct State *pCurrent = db->list + index;
  182. // copy from state to pCurrent
  183. copyState (state, pCurrent);
  184.  
  185. return;
  186. }
  187.  
  188. //printDatabase - print data of state array
  189. //input: pointer to Database struct
  190. //return: nothing
  191. void printDatabase (struct Database * db)
  192. {
  193. int i;
  194.  
  195. printf (" State name Year Capital Pop. rank\n");
  196. printf ("------------------------------------------------\n");
  197. for (i = 0; i < db->count; i++)
  198. printState(db->list+i);
  199.  
  200. return;
  201. }
  202.  
  203. //////////////////////// State functions //////////////////////////////
  204.  
  205. //initState - initializes a State struct with input data
  206. //input: pointer to State struct
  207. // name, year, capital, and population rank of state
  208. //return: true for success
  209. // false for fail
  210. int initState (struct State * state, char * name, int year, char * cap, int popRank)
  211. {
  212. char * stateName;
  213. char * capital;
  214. // if memory allocation is successful, store name
  215. if ( stateName = ( char * )malloc( sizeof( char ) * strlen( name ) ) )
  216. {
  217. strcpy( stateName, name );
  218. state->name = stateName;
  219. }
  220. else
  221. {
  222. printf("Not enough memory!\n");
  223. return 0;
  224. }
  225.  
  226. // store year
  227. state->year = year;
  228.  
  229. // if memory allocation is successful, store capital
  230. if ( capital = ( char * )malloc( sizeof( char ) * strlen( cap ) ) )
  231. {
  232. strcpy( capital, cap );
  233. state->cap = capital;
  234. }
  235. else
  236. {
  237. printf("Not enough memory!\n");
  238. return 0;
  239. }
  240.  
  241. // store population ranking
  242. state->popRank = popRank;
  243.  
  244. return 1;
  245. }
  246.  
  247. //deleteState - frees allocated memory inside a State struct
  248. //input: pointer to State struct
  249. //return: nothing
  250. void deleteState (struct State * state)
  251. {
  252. free( state->name );
  253. free( state->cap );
  254. free( state );
  255. }
  256.  
  257. //copyState - copies contents between two State structs
  258. //input: pointer to source State struct
  259. // pointer to destination State struct
  260. //return: nothing
  261. void copyState (struct State * from, struct State * to)
  262. {
  263. to->name = from->name;
  264. to->year = from->year;
  265. to->cap = from->cap;
  266. to->popRank = from->popRank;
  267. }
  268.  
  269. //printState - displays State data
  270. //input: pointer to State struct
  271. //return: nothing
  272. void printState (struct State * state)
  273. {
  274. printf ("%-17s%-8d%-18s%2d\n", state->name, state->year, state->cap, state->popRank);
  275.  
  276. return;
  277. }

The data from the file is read as state, year, capital, and population ranking.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster
degamer106 is offline Offline
131 posts
since Mar 2006
Jan 16th, 2007
0

Re: problem with freeing memory

Can't help much but I'm sure others would greatly appreciate it if you used the [code=c] tag.
Last edited by fesago90; Jan 16th, 2007 at 8:37 pm.
Reputation Points: 10
Solved Threads: 1
Newbie Poster
fesago90 is offline Offline
21 posts
since Jan 2007
Jan 16th, 2007
0

Re: problem with freeing memory

Click to Expand / Collapse  Quote originally posted by degamer106 ...
I'm almost finished with this program but the problem I'm having is with freeing the memory I allocated. Particularly in the area where I have pointers to strings.
And? What do you want us to do? Read every line of the code and tell you any errors we find?

Tell us any compilation errors. If it compiles, tell us the program output. Then say what you were expecting. Show the lines (or the whereabouts) of where this occurs. In this case, it would also be helpful if you showed us the file you're trying to read.

Click to Expand / Collapse  Quote originally posted by fesago90 ...
Can't help much but I'm sure others would greatly appreciate it if you used the [code=c] tag.
He doesn't have to as long as he tells us what is wrong with the code.
Last edited by John A; Jan 16th, 2007 at 8:40 pm.
Team Colleague
Reputation Points: 2240
Solved Threads: 338
Vampirical Lurker
John A is offline Offline
5,055 posts
since Apr 2006
Jan 16th, 2007
0

Re: problem with freeing memory

never mind i figured out the problem(s)
Reputation Points: 10
Solved Threads: 0
Junior Poster
degamer106 is offline Offline
131 posts
since Mar 2006
Mar 29th, 2008
0

Re: problem with freeing memory

Click to Expand / Collapse  Quote originally posted by degamer106 ...
never mind i figured out the problem(s)
I think I'm having a similar problem. Any chance you could describe how you fixed this problem? Or, what the problem was?
Reputation Points: 10
Solved Threads: 0
Newbie Poster
bbcannon is offline Offline
1 posts
since Mar 2008
Mar 30th, 2008
1

Re: problem with freeing memory

Click to Expand / Collapse  Quote originally posted by bbcannon ...
I think I'm having a similar problem. Any chance you could describe how you fixed this problem? Or, what the problem was?
Most memory problems boil down to the program either trying to access/free memory that it didn't allocate (resulting in crashes/segmentation faults), or not freeing memory after the software is finished using it (resulting in memory leaks). Since everyone's code is different, please start a new thread with the exact issue you're experiencing.
Last edited by John A; Mar 30th, 2008 at 1:16 am.
Team Colleague
Reputation Points: 2240
Solved Threads: 338
Vampirical Lurker
John A is offline Offline
5,055 posts
since Apr 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: read to end of line problem
Next Thread in C Forum Timeline: Basic C assistance





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC