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

标签 c memory

我正在编写一个函数,它接收一个字符串并从中提取标记,并将它们存储在堆栈中。有一个叫currentToken的变量,以内存开头只有1个字符:

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

随着 token 的形成,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);

关于c - 关于在 C 中为字符串变量分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21652012/

相关文章:

ios - 如何调试 NSZombies 和内存泄漏?

c++ - 如何使用 OpenGL 确保 Qt 中动画的适当速度?

c - c中的无符号整数

java - 子类对象的创建是否也会创建其父类(super class)的对象?

memory - 拟合微分方程组参数时 Mathematica 内存不足

c++ - 为什么linux上一个动态链接的可执行文件在自己的内存空间里有libc的完整内存空间?

c++ - 序列化和反序列化 uint64_t - 不同平台上的不同结果

c - 删除填充数据

c - 使用 C 关闭系统不起作用

matlab中没有释放内存?