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.