Advertisement
mostafaxx

allocating mem using glib

Sep 2nd, 2012
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <glib.h>
  4.  
  5. typedef struct
  6. {
  7.     int item_id;
  8.     unsigned char *item_name;
  9.     double item_price;
  10.     int item_stock_count;
  11. } item_data;
  12.  
  13. void print_item(item_data *item_ptr)
  14. {
  15.     printf("item_id: %i,\n item_name: %s,\n item_price: %g,\n item_stock: %i\n",
  16.         item_ptr->item_id,
  17.         item_ptr->item_name,
  18.         item_ptr->item_price,
  19.         item_ptr->item_stock_count);
  20. }
  21.  
  22. int main()
  23. {
  24.     GSList *items_list1 = NULL, *iterator = NULL;
  25.     item_data *tmp_item = NULL;
  26.     int i = 0;
  27.     char *tmp_str = NULL, *tmp_str2 = NULL;
  28.    
  29.     tmp_str = malloc(1);
  30.  
  31.     for(i = 0; i < 3; i++)
  32.     {
  33.         sprintf(tmp_str, "%d", i);
  34.  
  35.         tmp_str2 = (unsigned char *)malloc(100);
  36.         if (tmp_str2 == NULL)
  37.         {
  38.             fprintf(stderr, "Couldn't allocate memory\n");
  39.             return -1;
  40.         }
  41.  
  42.         strcpy(tmp_str2, "item_num num: ");
  43.         strcat(tmp_str2, tmp_str);
  44.  
  45.  
  46.         // ***Allocate memory using glib***
  47.         tmp_item = g_new(item_data, 1);
  48.         if (tmp_item == NULL)
  49.         {
  50.             fprintf(stderr, "Couldn't allocate memory\n");
  51.             return -1;
  52.         }
  53.  
  54.         tmp_item->item_id = i;
  55.         tmp_item->item_name = tmp_str2;
  56.         tmp_item->item_price = 100*(i+1);
  57.         tmp_item->item_stock_count = 10*(i+1);
  58.  
  59.         items_list1 = g_slist_append(items_list1, tmp_item);
  60.     }
  61.  
  62.     // Clean up
  63.     for(iterator = items_list1; iterator != NULL; iterator=iterator->next)
  64.     {
  65.         free(((item_data*)iterator->data)->item_name);
  66.         g_free(iterator->data);
  67.     }
  68.  
  69.     for(iterator = items_list1; iterator != NULL; iterator=iterator->next)
  70.         print_item((item_data*)iterator->data);
  71.  
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement