I made a simple base converter and the very first thing it does is it gets a string from the user. I wanted the string to be dynamic, so I did this:
char *getStr() {
char *str = NULL;
/*LOOP THAT USES getc() TO SAVE CHARS INTO THE STRING AND GROWS IT USING realloc() IF NEEDED*/
return str;
}
int main() {
char *str;
str = getStr();
//SOME STUFF HAPPENS HERE WITH THE str. IT REMAINS THE SAME LENGTH.
free(str) //IS THIS THE RIGHT PLACE TO FREE IT?
}
So, is free() in the right place here? I understand that since both str pointers point to the same address it should work, right? Also, by the way, how does free() know where to stop deallocating, when it only has the first address? This may be pretty obvious, but I wanna make sure.
In your example, this is the right place for it. The simplest free are called when you are just no need for the data anymore. The tricky part in my experience is when things don't go as planned, or when your program can exit with multiple ways.
Take a look at this dummy program that has absolutely no real purpose. A program that takes an integer, if this integer has a value superior to 10, the program will add 1 to it. If not, it will exit the whole program with exit (1)
static void add_one_to_num(int *num)
{
if (*num < 10)
{
free(num);
exit(1);
}
*num = *num + 1;
}
int main()
{
int *num;
num = malloc(sizeof(int));
printf("Enter a number higher than 10: ");
scanf("%d", num);
add_one_to_num(num);
printf("num: %d\n", *num);
free(num);
return (0);
}
In this program, we might exit at the function add_one_to_num so you need to free that pointer in that place. By writing more and more programs you will get the hang of it, because it's actually very logical and not at all chaotic (It could be a pain in the neck for large programs to track down all allocated memories throughout all the functions the pointers are passed to ). just make sure to free when you longer need the data, or when something changes the natural flow of your program.