Giwrgos Tsopanoglou
Giwrgos Tsopanoglou

Reputation: 1215

How to manage memory returned from function in C

I want to make a tokenization sub-program which will work like this :

The idea was simple ( i think ) but I came up with a difficult problem. When making the substring function, I realized that it was a memory leak hole. The only way i can think of making a substring function is this :

    char* sub = ( char* ) malloc ( ( some_length + 1 ) * sizeof( char ) );

    for ( i = start_index ; i < some_length ; i++ )
    {
         sub[ i - start_index ] = source_string[i];
    }

    sub[ some_length ] = '\0'

    return sub;

But the problem is that when using the substring function, i won't have the ability to free that memory afterwards.

    // Example usage

    TokenStruct* MyToken = CreateToken( substring( input , start , length ) );

Some may suggest that i should free memory inside the CreateToken function but this seems like a VERY bad idea to me because it will make CreateToken's code very dependent on the substring function. Also, the substring function might be used in many other functions.

I had an idea of keeping a table of pointers and free them before terminating the program but seems kind of sketchy...

What do you think guys? What is the best way to deal with this kind of problem?

Thanks in advance!

Upvotes: 1

Views: 99

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

This is a very common problem in C and other languages of the same type. There are basically three solutions to this:

  1. Either do the call separately and then free the memory afterwards.
  2. Keep the pointer in the object (MyToken in your case), and free the string when you free the object.
  3. Use an array, and pass it in (together with a maximum length) to the function.

Since the created pointer have to be "live" for the life of your object (MyToken) anyway, then I suggest method number two.

Upvotes: 3

Related Questions