Gilson Urbano

Authored Comments

Thanks for the great article. In the section 'Heap storage', I noticed that the main function checks if the /* malloc failed */, but since we are initializing *heap_nums in the same function (get_heap_array) we are trying to allocate memory, we need to add validation before trying to access the array to avoid segmentation failure (SIGSEGV) in case of allocation failure.

int *get_heap_array(unsigned n) {
int *heap_nums = malloc(sizeof(int) * n);

/* Check heap allocation */
if (NULL == heap_nums) /* failure? */
return NULL; /* if so, return NULL */

unsigned i;
for (i = 0; i < n; i++)
heap_nums[i] = i + 1; /* initialize the array */

/* stack storage for variables heap_nums and i released
automatically when get_num_array returns */
return heap_nums; /* return (copy of) the pointer */

I hope to learn more from you!