I want to make a tokenization sub-program which will work like this :
- Read user input
- Find tokens
- Use a substring function to get each token
- Store each token in a struct
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!
TokenStructstore the token by reference (char *). And definesubstring()as a source/creator, which's result needs to be deleted, likestrdup()for example.#include <string.h>and usestrncpy()instead of yourfor-loop.mallocin a C program. Andsizeof(char)is1.