2

I'd like to free automatically multiple malloced memory at the end of a program in C.

For example :

str1 = malloc(sizeof(char) * 10);
str2 = malloc(sizeof(char) * 10);
str3 = malloc(sizeof(char) * 10);

I don't want a function like this :

void   my_free()
{
    free(str1);
    free(str2);
    free(str3);
}

but a function which free all the memory allocated during the program.

3
  • 3
    you need to free manually. Commented Jul 8, 2015 at 9:20
  • I don't think there is such a function... Commented Jul 8, 2015 at 9:20
  • another option is not to use heap allocations (malloc) but use stack allocation. Commented Jul 8, 2015 at 9:47

2 Answers 2

7

but a function which free all the memory allocated during the program.

There's no such function in C. C doesn't do memory management automatically. So it's your responsibility to track the memory allocations and free them appropriately.

Most modern operating systems (perhaps, not embedded systems) would reclaim the memory allocated during execution at process termination. So you can skip calling free(). However, if your application is a long running one then this will become a problem if it keeps allocating memory. Depending your application, you may devise a strategy to free memory appropriately.

Sign up to request clarification or add additional context in comments.

Comments

1

As Blue Moon pointed out in his answer, one of the main features of C compared to other languages is the missing memory management. While this gives you a lot of freedom it can on the other hand lead to severe bugs in your code.

Technically the detection of memory leaks is not possible with a confidence level of 100%, but there are quite powerful static code analyzers out there to guide you.

In the last embedded project I worked on we used FlexeLint. It is costly for non-commercial products but the benefit is enormours. A lot of potential bugs and leaks could be detected with such a static analyzer without even executing the code.

There is another static analyzer, free of cost for open source projects called Coverity Scan. I did not try it myself but it is probably worth a shot.

After witnessing what a good analyzer like FlexeLint is able to detect beyond mere compilation errors, I personally would not launch another C Project without such analyzis tools in place.

While this is not a direct answer to your question, it can be an improvement to your workflow because such errors as forgetting a free call will be detected in most cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.