1

I'm writing a function that receives a string and extracts the tokens from it, storing them in a stack. There is a variable called currentToken, which starts with memory for only 1 character:

char *currentToken = ( char * )malloc( sizeof( char ) );

As the token is being formed, currentToken is extended through realloc to accomodate the new character. Everytime currentToken is complete, it is added to the stack by reference. Then, I try to "reset" it (as if I was setting it to an empty string) freeing its memory and allocating it again. Does it destroy the data previously included in the stack? If so, how do I fix this problem? Thanks in advance.

The stack is implemented as a structure, and it is initialized right from the beginning:

typedef struct stackOfStrings {
    char **array;
    int numberOfElements;
} StackOfStrings;

/* Initializes the stack of strings: */
void initializeStackOfStrings( StackOfStrings *sPtr )
{
    sPtr->numberOfElements = 0;
    sPtr->array = ( char ** )malloc( 1 * sizeof( char * ) );
}

/* Inserts str at the top the stack of strings, returning 1 if it succeeds, or 0
otherwise: */
int pushOnStackOfStrings( StackOfStrings *sPtr, char *string )
{
    int length = string_length( string );

    ++( sPtr->numberOfElements );

    sPtr->array = realloc( sPtr->array, ( sPtr->numberOfElements ) * sizeof( char * ) );

    if ( sPtr->array == NULL )
    {
        return 0;
    }

    *( sPtr->array + ( sPtr->numberOfElements - 1 ) ) = ( char * )malloc( length * sizeof( char ) );

*( sPtr->array + ( sPtr->numberOfElements - 1 ) ) = string;

return 1;

}

1 Answers1

0

try this

void initializeStackOfStrings( StackOfStrings *sPtr )
{
    sPtr->numberOfElements = 0;
    sPtr->array = NULL;
}
...
sPtr->array[sPtr->numberOfElements - 1] = ( char * )malloc( (length+1) * sizeof( char ) );
strcpy(sPtr->array[sPtr->numberOfElements - 1], string);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70