Free memory in C Programming | Sololearn: Learn to code for FREE!


Free memory in C Programming

How can I free memory of an array of pointers without knowing the size of the array? For example: char *planet[]

4/8/2021 3:35:04 PM


9 Answers

New Answer


thank you Coder Kitten


The array is used as parameter for a function. Thanks all, I solved the problem by using pointer to pointer to traverse though the array. Martin Taylor Coder Kitten


You don't need to know the size in order to free the memory, though you do need to know the size to allocate it. Incidentally, you can't declare an array of char pointers like that if you want to use dynamic memory allocation. #include <stdio.h> #include <stdlib.h> int main() { char **planets; planets = malloc(sizeof(char*) * 8); planets[0] = "Mercury"; planets[1] = "Venus"; planets[2] = "Earth"; planets[3] = "Mars"; planets[4] = "Jupiter"; planets[5] = "Saturn"; planets[6] = "Uranus"; planets[7] = "Neptune"; for(int i=0; i<8; i++){ printf("%s\n", planets[i]); } free(planets); // <-- freeing the memory return 0; } If you declare the array using square brackets then you need to specify a constant. If you do this then the array is of fixed size and cannot be freed. Your only other option is to use a Variable Length Array (VLA), which uses the stack.


Thanks 🌹 for the Help


char **planets; planets = malloc(sizeof(char*) * 8); this function is use for the memory of numbers in c.