I wrote the following code today to experiment with returning pointers to allocated memory.
The program works fine but I do have a few questions:
-
To allocate the memory for the return value of
rmchI userealloc. I understand the function and what it does for the most part I’m just quite not sure what the point of(char *)in the lineret = (char *) realloc(ret, c * sizeof(char));I understand thatrealloc(ret, c * sizeof(char));resizes the allocated memory to #c chars, but what does the(char *)part do? -
I do not free the allocated memory that
retpoints to anywhere, but I do free a pointer toretwhich is called in mymainfunction. What is happening to the allocated memory? If it is not being freed how would I go about freeing it?
Code
#include <stdio.h>
#include <stdlib.h>
char* rmch(char *str, char ch)
{
char *ret = NULL;
int c = 0, i;
for(i = 0; str[i] != '\0'; i++)
{
if(str[i] != ch)
{
c++;
ret = (char *) realloc(ret, c * sizeof(char));
ret[c - 1] = str[i];
}
}
ret[c] = '\0';
return ret;
}
int main(void)
{
char *foo = rmch("f o o", ' ');
printf("%s", foo);
free(foo);
return 0;
}
Freeing Foo in main will free the ret you’ve realloc’d in rmch.
The reason being is free() goes to the address specified by the pointer which is returned by rmch.
Also, as you have tagged this post with the “C” tag, you should never cast the return value of allocations.
void *'sare automagically, implicitly promoted to whatever they are stored in, provided they were given the correct byte sizes during allocation.As an aside, you should never directly store any allocated memory directly into the pointer you are using/will be using as this can lead to memory leaks if the pointer returned is NULL and you were still pointing to old memory.
Better to do this:
And then you would need to check for a NULL return in your main as well.