关于C中为字符串变量分配的内存

关于C中为字符串变量分配的内存,c,memory,C,Memory,我正在编写一个函数,该函数接收字符串并从中提取令牌,将它们存储在堆栈中。有一个名为currentToken的变量,它仅以1个字符的内存开始: char *currentToken = ( char * )malloc( sizeof( char ) ); 当标记形成时,currentToken通过realloc扩展以容纳新字符。每次currentToken完成时,都会通过引用将其添加到堆栈中。然后,我尝试“重置”它(就像我将它设置为空字符串一样),释放它的内存并再次分配它。它是否会销毁以前包含

我正在编写一个函数,该函数接收字符串并从中提取令牌,将它们存储在堆栈中。有一个名为currentToken的变量,它仅以1个字符的内存开始:

char *currentToken = ( char * )malloc( sizeof( char ) );
当标记形成时,currentToken通过realloc扩展以容纳新字符。每次currentToken完成时,都会通过引用将其添加到堆栈中。然后,我尝试“重置”它(就像我将它设置为空字符串一样),释放它的内存并再次分配它。它是否会销毁以前包含在堆栈中的数据?如果是,如何解决此问题?提前谢谢

堆栈实现为一个结构,并从一开始就初始化:

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;
}试试这个

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);

你正在失去记忆。最后两行,您正在分配一些内存,然后通过将
string
分配给它而丢失指向该内存的指针。如果它是正确的C字符串(即以null结尾),则更容易,否则使用
memcpy
@glglglgl,如果您不强制转换
malloc()
则会得到警告。@stephenasku为什么会是警告?从
malloc()
转换malloc的返回值失败时,如果您收到警告,则说明您使用了错误的语言,或者使用了错误的语言。