0

I'm new to programming and am trying to do some practice problems in C. I've come across the following prompt:

/*
Pascal's Triangle
Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 * Return an array of arrays.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

I finished the problem using a two-dimensional array as a first attempt and then tried doing it by using malloc (as specified in the problem) and got a bit stuck. I looked over some solutions and found one that somewhat matched my approach:

// Source: https://github.com/vli02/leetcode/blob/master/118.%20Pascal's%20Triangle.c
int** generate(int numRows, int** columnSizes) {
    int i, j;
    int *buff, **p;
    p = malloc(numRows * sizeof(int *));
    *columnSizes = malloc(numRows * sizeof(int));
    //assert(p && *columnSizes);
    for (i = 1; i <= numRows; i ++) {
        buff = malloc(i * sizeof(int));
        //assert(buff);
        p[i - 1] = buff;
        (*columnSizes)[i - 1] = i;
        buff[0] = 1;
        for (j = 1; j < i - 1; j ++) {
            buff[j] = p[i - 2][j - 1] + p[i - 2][j];
        }
        buff[i - 1] = 1;
    }
    return p;
}

All I want to ask is, how is this solution correct if the corresponding address to the buff pointer is changed through every loop, but the blocks of memory allocated in each loop are never freed? Wouldn't this cause a memory leak? As far as I've seen, malloc will not free the previously allocated memory. I've just begun coding in C, so I'm not sure if something is happening under the hood that I should know about. Any help would be greatly appreciated.

  • 1
    `p[i - 1] = buff;` retains the buffer allocated in the for-loop on each iteration. This is a generic pointer-to-pointers implementation. Unrelated, this code would be 10x easier to read if you embraced the simple fact that arrays are zero-base indexed and looped accordingly. – WhozCraig Jun 04 '22 at 23:07
  • @WhozCraig Thanks for the reply; I should've noticed that. To free the memory, would you iterate over the "p" array and call free at each index? – user_289389232 Jun 04 '22 at 23:11
  • Yes, and then free the the address held in `p` when done. All of that, I assume, is done by the caller, since it is obviously pointless to do it here. – WhozCraig Jun 04 '22 at 23:12
  • @user_289389232 Yes, you would free each element of `p`, then free `p` itself. – dbush Jun 04 '22 at 23:12
  • @WhozCraig, thank you so much. If you know of any resources to best learn more concepts in C, it would be greatly appreciated if you could share them. – user_289389232 Jun 04 '22 at 23:15
  • See: https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – Craig Estey Jun 05 '22 at 00:47

0 Answers0