OriginalGriff described the issue. In your code there is nothing that releases the memory that was allocated. You have the function
take_content
which allocates memory for content so there needs to be a corresponding
free_content
function that de-allocates or releases that memory by calling
free
. The function
str_make_index
also allocates content's memory but the same
free_content
function can be used to release it.
Another place to be aware of is the function
return_size
which allocates a temporary buffer and that buffer is leaked. What should happen is the return value of that function must be saved and then released (via
free
) after atoi is called. Actually, a much better option would be to change
return_size
to do what its name implies. It makes little sense to return a string in my opinion. That function should look like this :
int return_size( char* content )
{
char string[ 100 ] = { 0 }; int value = 0;
int index = 0;
int inside = 0;
while( content[index] )
{
if( isdigit( content[ index ] )
{
string[inside++] = content[index];
}
index++;
}
value = atoi( string );
return value;
}
Another improvement you can make is in
take_name
where a buffer of 18 characters is allocated. That also makes little sense when you could make file_name a character string of that size instead. Regardless, is a fixed-size buffer of 18 characters safe for all possible inputs? That seems unlikely to me so I would change your function to look like this :
char* take_name( int size, char** array )
{
char * name = NULL;
int y = 1;
if( size > 0 )
{
name = array[y]; }
return name; }
This allows you to accommodate a file name of any size supported by the OS and has the added benefit of not allocating any memory so no release is necessary.
Another thing - I recommend calling
calloc
instead of
malloc
because it clears the memory that is allocated - that's what the C stands for.
Lastly, if you use Visual Studio as your compiler it has memory tracking facilities built in so if you add this sequence in your code modules it will tell you where the leaks originate:
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#endif
I do this in all my code to make certain it is free of leaks. If you do not use Visual Studio there are likely to be other mechanisms available.