| |||||||||||
| |||||||||||
Memory allocation and freeing - demo of principles
Memory Management example from a Well House Consultants training course
More on Memory Management [link]
Source code: trinamic.c Module: C212
/* Memory allocation and freeing - demo of principles
In this example, I'm going to read a file of records .. an unknown number of records, each of an unknown length, and store them in data structures that are just big enough to hold them. The alternatives is to allow enough memory for the biggest possible lines and the biggest possible number of lines. But that would be very wasteful of memory and place an arbitary limit on the application! The only limit is 256v characters per line in the input buffer */ #include <stdlib.h> #include <stdio.h> #include <string.h> #define MAXLINELEN 257 /* Data is at http://www.wellho.net/data/railstats.xyz */ int main() { char **mydata = NULL ; int nread = 0; int k; char *itsat; char myreadbuffer[MAXLINELEN]; FILE * infile; infile = fopen("railstats.xyz","r"); while (fgets(myreadbuffer,MAXLINELEN-1,infile)) { /* Add a check for line length == MAXLINELEN-1 ?? */ /* Just in case any individual lines hit the limit */ /* Clever bit - allocate just enough heap memory for the line read! */ itsat = calloc(sizeof(char), strlen(myreadbuffer) + 1); /* Very Clever bit - EXTEND the mydata 'array' so that it can hold an extra pointer to the memory just allocated above */ mydata = realloc(mydata,(nread+1) * sizeof(char *)); /* And store the address of the string (got in the clever bit) into the newly extended location, building into an array of pointers to strings, with each element dynamically extending. Two alternative syntaxes are shown here - I have commented one of them out, but you can use either! */ *(mydata+nread) = itsat; /* mydata[nread] = itsat; */ /* Finally, copy the string that has been read into the buffer into the newly allocated memory. You may be told strncpy is safer */ strcpy(itsat,myreadbuffer); /* And in C, you need to keep note of how long arrays are / how much data you have in them. This csn be done by holding a special (cardinal) value at the end which is what is done with strings (it's a \0 character), or by keeping a separate counter variable which is what I have done here */ nread++; } /* For demonstration - print out all the data from the complete structure */ #ifdef DEMO for (k=0; k<nread; k++) { printf("%s",mydata[k]); } #endif /* What would we do with our data? Perhaps report on all stations which has between 220 and 370 passengers in a the final year of our data (that's the last column), outputting their industry standard 3 letter code (the second data column). Data tab delimited. */ for (k=0; k<nread; k++) { char *sep1; char tlc[4],spcount[10]; int pcount; sep1 = strchr(mydata[k],'\t'); strncpy(tlc,sep1+1,3); tlc[3] = '\0'; sep1 = strrchr(mydata[k],'\t'); strncpy(spcount,sep1+1,9); pcount = atoi(spcount); if (pcount == 0) continue; /* Skip over NULL entries */ if (pcount < 220 || pcount > 370) continue; /* Just print out in a range */ printf("code, count %s %d\n",tlc,pcount); } /* If this is long running, release the memory when no longer neededed */ for (k=0; k<nread; k++) { free(mydata[k]); } free(mydata); /* Don't forget the outer array too! */ } /* Here is some sample output munchkin:xc grahamellis$ g++ -o transport transport.cpp transport.cpp: In function ‘int main()’: transport.cpp:38: warning: deprecated conversion from string constant to ‘char*’ transport.cpp:39: warning: deprecated conversion from string constant to ‘char*’ munchkin:xc grahamellis$ ./transport building Swindon building Cheltenham Spa using can take 581 to Swindon using can take 105 to Cheltenham munchkin:xc grahamellis$ */ Learn about this subject
This module and example are covered on the following public courses:
* Learning to Program in C * Learning to program in C and C++ * Programming in C * C and C++ Programming * Learning to program in C and C++ * C and C++ Programming Also available on on site courses for larger groups Books covering this topic
Yes. We have over 700 books in our library. Books
covering C and C++ are listed here and when you've selected a
relevant book we'll link you on to Amazon to order.
Other Examples
This example comes from our "Memory Management" training module. You'll find a description of the topic and some
other closely related examples on the "Memory Management" module index page.
Full description of the source code
You can learn more about this example on the training courses listed on this page,
on which you'll be given a full set of training notes.
Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License. Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre. • The Horse's mouth provides a daily tip or thought. • Further resources are available via the resources centre. • All of these resources can be searched through through our search engine • And there's a global index here. Purpose of this website
This is a sample program, class demonstration or answer from a
training course. It's main purpose
is to provide an after-course service to customers who have attended our
public private or
on site courses, but the examples are made
generally available under conditions described below.
Web site author
Conditions of use
Past attendees on our training courses are welcome to use individual
examples in the course of their programming, but must check
the examples they use to ensure that they are suitable for their
job. Remember that some of our examples show you how not to do
things - check in your notes. Well House Consultants take no responsibility
for the suitability of these example programs to customer's needs.
This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details. Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request. |
| ||||||||||
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho PAGE: http://www.wellho.net/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb |