Re: Memory allocation using g_malloc



On Mon, Jun 19, 2006 at 11:59:07PM +0100, Yianni wrote:
[...]

OK, I'll bite. Here is a little program implementing a dynamic array
with the help of realloc. Basically it defines a data type (as a pointer
to a struct holding the max number of slots allocated, the number of
actually used slots and a pointer to an (initially empty) array of
character pointers, which gets resized as needed.

Three functions comprise the interface to this thing:

  filelist_new() returns a new (empty) filelist thingie
  filelist_add(fl, name) adds a name to the filelist
  filelist_delete() frees all allocated space.

Of course, for more fancy stuff, the rich data types offered by glib are
worth a look. Sometimes, a GList or a GSList are just more flexible
(albeit with more overhead).

Here it goes (but it's getting quite off-topic):
(WARNING: very lightly tested. Error recovery next to non-existent. Use
at your own risk. Yadda, yadda, yadda).

 +------------------------------------------------------------
 | /* filelist.c */
 | #include <stdio.h>
 | #include <stdlib.h>
 | #include <string.h>
 | #include <sys/types.h>
 | #include <dirent.h>
 | 
 | typedef struct {
 |   int nnames;
 |   int maxnames;
 |   char **names;
 | } _filelist;
 | 
 | typedef _filelist* filelist;
 | 
 | filelist filelist_new()
 | {
 |   filelist fl = malloc(sizeof(_filelist));
 |   fl->nnames = fl->maxnames = 0;
 |   fl->names = NULL;
 |   return fl;
 | }
 | 
 | void filelist_add(filelist fl, char *name)
 | {
 |   void *blub;
 |   if(fl->nnames >= fl->maxnames) { /* no room: grow */
 |     /* adjust growth and start size to your tastes */
 |     int newmax = fl->maxnames;
 |     if(newmax > 5) newmax *= 1.2; /* 20 percent growth */
 |     else newmax = 16; /* arbitrary start size, should be >= 5 */
 |     fl->names = realloc(fl->names, newmax*sizeof(char *));
 |     fl->maxnames = newmax;
 |   }
 |   fl->names[fl->nnames++] = strdup(name);
 | }
 | 
 | void filelist_delete(filelist fl)
 | {
 |   int i;
 |   for(i=0; i<fl->nnames; i++) free(fl->names[i]); /* free strings */
 |   free(fl->names); /* free array of pointers */
 |   free(fl); /* free struct */
 | }
 | 
 | int main(int argc, char *argv[])
 | {
 |   DIR *d;
 |   struct dirent *e;
 |   filelist fl;
 |   int i;
 | 
 |   if( (d = opendir("/home/tomas")) == NULL ) {
 |     fprintf(stderr, "AAARGH\n");
 |     exit(1);
 |   }
 | 
 |   fl = filelist_new();
 | 
 |   while( (e = readdir(d)) != NULL ) {
 |     filelist_add(fl, e->d_name);
 |   }
 | 
 |   closedir(d);
 | 
 |   for(i=0; i<fl->nnames; i++) {
 |     printf("%s\n", fl->names[i]);
 |   }
 |   return 0;
 | }
 +------------------------------------------------------------


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]