Memory leak with strtok?

This question occurred to me today as I was working with strtok. If I create a new array of char with "new char[ size ]", then use strtok on that char string, is there any way to delete the whole array and reclaim all the memory after using strtok? I suspect that the "delete [] *ptr_to_char_array;" statement will only reclaim the memory of the first token created, but I'm a self-taught programmer and I'm just guessing here. Thoughts?
Last edited on
I just came across an example of this happening in my code...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	string input;
	char *p;
	stack<double> RPN_stack;
	int c;
	double a, b, n;

	cout << "Enter RPN string: ";
	getline( cin, input );
	p = new char[ input.size() + 1 ];
	strcpy( p, input.c_str() );
	p = strtok( p, " " );
	while ( p ) {
                 //rest of program
                 p = strtok( NULL, " " );

Once I create the new char array and then break it up with strtok, I think I can only access the first token of that original string that was put into *p. So, I think I can only delete and reclaim that first token, not the entire string first copied into p.
1) Am I right in thinking there is a loss of memory due to the string tokens I can no longer access after strtok()?
2) If so, is there a way to delete that entire char array?
3) The overall goal of this code segment is to read in a variable size input string from cin, divide up that input into tokens, and analyze the tokens for use later in the program. I've found that strtok can only take a non-const char*, but I seem to only be able to get a string object to convert into a const char* via string::c_str(). So I work around it with the pointer p and allocating a new char array based on string, essentially creating a second copy of the input. I suspect this isn't the most efficient way to do things. Any better solution to this problem?

By the way, I'm teaching myself C++ for fun from a library book I found (C++ Without Fear), so forgive me if I'm missing something obvious.
Last edited on
No memory loss. The only thing that strtok is doing is replacing the tokens found with '\0'. That is is not going to affect the delete or freeing of the memory. The memory manager knows how much memory to give back when it is freed or deleted.
So adding a line later on in the program like
delete [] p;
would suffice to reclaim the memory originally allocated by "new"?
Yes. What is or was in the array doesn't change what delete is going to do.
Topic archived. No new replies allowed.