Advertisement
AneMou

C - Realloc Memory Leak (corrected)

May 16th, 2024 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* ... */
  5.  
  6. // we now want our addToList function to return something to handle errors
  7. int addToList(struct list *myList, int item);
  8.  
  9. /* ... */
  10.  
  11.     // Inside the main function
  12.  
  13.     // Add any number of items to the list specified by the amount variable
  14.     amount = 44;
  15.     for (int i = 0; i < amount; i++) {
  16.         if ( addToList(&myList, i + 1) ) {
  17.             free(myList.data);
  18.             myList.data = NULL;
  19.             return -1;
  20.         }
  21.     }
  22.  
  23. /* ... */
  24.  
  25. // This function adds an item to a list
  26. // if an error occured the functions returns 1, else 0
  27. int addToList(struct list *myList, int item) {
  28.    
  29.     // If the list is full then resize the memory to fit 10 more items
  30.     if (myList->numItems == myList->size) {
  31.         myList->size += 10;
  32.         int *temp = NULL;
  33.         temp = realloc( myList->data, myList->size * sizeof(int) );
  34.         if (NULL == temp) {
  35.             perror("Failed to reallocate memory, the program should stop");
  36.             return -1;
  37.         }
  38.         myList->data = temp;
  39.         temp = NULL;
  40.     }
  41.    
  42.     /* ... */
  43.     return 0;
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement