I believe I am doing this right but wanted to make sure. In a program I am using two pointers that point to allocated memory returned by a function. When I finish using that memory I free() it, but then I use those same pointers to point at a new allocated memory space. Here is my program to give an example of what I mean (Commented to show my thought process):
int main(void)
{
char *data, *url;
int i = 1;
while(i)
{
printf("Enter URL: ");
if(!(url = getstr())) return 1; //url now points to allocated memory from getstr();
if(strlen(url) <= 0) i = 0;
if(data = readsocket(url, 80, "http")) printf("\n%s\n\n", data); //data now points to allocated memory from readsocket();
else printf("\n\n");
free(url); //free allocated memory that url points to url
free(data); //free allocated memory that data points to data
}
return 0;
}
Is this correct, or is there a better more generally preffered method of doing this? Or am I just completely doing it wrong?
Assuming your functions
getstrandreadsocketmalloc the memory internally then this is perfectly fine.My only suggestion is that it’s often helpful to allocate memory in the same scope that you free it, this often helps reason about when things need to be freed.
For example:
It can be nice to do this using goto, if you have lots of objects and exit points.
If your objects get more complex and require a lot of work to create and destroy then you can wrap malloc and free, but it’s critical you apply exactly the same rules to your create/destroy functions as you would to malloc/free to avoid leaks. As a matter of good practice you should always have a destroy to match a create, even if it just wraps free. It’s much harder to go wrong that way.