【问题标题】:About the memory allocated for a string variable in C关于为 C 中的字符串变量分配的内存
【发布时间】:2014-02-08 21:26:31
【问题描述】:

我正在编写一个函数,它接收一个字符串并从中提取标记,并将它们存储在堆栈中。有一个变量叫做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;

}

【问题讨论】:

  • 你正在失去记忆。最后两行,您正在分配一些内存,然后通过分配string 来丢失指向该内存的指针。
  • 如果是正确的 C 字符串(即空终止)strcpy 更容易,否则使用 memcpy
  • @glglgl,如果你不投malloc(),你会收到警告。
  • @StephenRasku 为什么会是一个警告?转换 malloc 的返回值不是完成的事情。
  • 如果您在从malloc() 转换返回失败时收到警告,那么您要么使用了错误的语言,要么使用了错误的语言。

标签: c memory


【解决方案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);

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2014-12-11
    相关资源
    最近更新 更多