c - 分配内存并在c中保存字符串

标签 c string malloc free

我想知道为什么下面的代码不起作用

int main(int argc, char **argv)
{
     char *test = (char*) malloc(12*sizeof(char));
     test = "testingonly";
     free(test);
}

考虑之后,我的假设是首先我在内存中为 12 个字符分配空间,但下一行中的赋值在堆栈上创建一个字符数组,并将其内存地址传递给测试。所以 free() 试图释放堆栈上不允许的空间。对吗?

那么在堆上保存字符串的正确方法是什么?以下是常见的方式吗?

int main(int argc, char **argv)
{
     char *test = (char*) malloc(12*sizeof(char));
     strcpy(test, "testingonly");
     free(test);
}

最佳答案

char *test = (char*) malloc(12*sizeof(char));

        +-+-+-+-+-+-+-+-+-+-+-+-+
test--->|x|x|x|x|x|x|x|x|x|x|x|x|   (uninitialized memory, heap)
        +-+-+-+-+-+-+-+-+-+-+-+-+

test = "testingonly";

        +-+-+-+-+-+-+-+-+-+-+-+-+
test +  |x|x|x|x|x|x|x|x|x|x|x|x|
     |  +-+-+-+-+-+-+-+-+-+-+-+-+
     |  +-+-+-+-+-+-+-+-+-+-+-+-+
     +->|t|e|s|t|i|n|g|o|n|l|y|0|  
        +-+-+-+-+-+-+-+-+-+-+-+-+

free(test); // error, because test is no longer pointing to allocated space.

无需更改指针 test,您需要将字符串 "testingonly" 复制到分配的位置,例如使用strcpy 或使用 strdup。请注意,如果可用内存不足,mallocstrdup 等函数将返回 NULL,因此应进行检查。

char *test = (char*) malloc(12*sizeof(char));
strcpy(test, "testingonly");

        +-+-+-+-+-+-+-+-+-+-+-+-+
test--->|t|e|s|t|i|n|g|o|n|l|y|0|
        +-+-+-+-+-+-+-+-+-+-+-+-+

char *test = strdup("testingonly");

        +-+-+-+-+-+-+-+-+-+-+-+-+
test--->|t|e|s|t|i|n|g|o|n|l|y|0|
        +-+-+-+-+-+-+-+-+-+-+-+-+

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

相关文章:

javascript - 奇怪的 Javascript 字符串错误

java - for 循环内的打印语句导致多个输出而不是一个输出,如何在不使用 "return"的情况下解决此问题?

c - "Pointer being freed was not allocated"发生在 mac 但不是在 windows 7

c - 从堆栈结构 C 释放指针

c - 如何避免 realloc 溢出?

C忽略 "if"指令

c - 如何清理由 "json_object_new_string"创建的 json 对象?

c - 删除字符串末尾的路径分隔符

python - 如何从 lldb python API 访问 C 数组浮点值

c# - 为用户提供转义字符串的最佳方式