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

plu*_*uck 22 c string malloc free

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

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

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

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

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

And*_*rsK 66

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.
Run Code Online (Sandbox Code Playgroud)

test您需要"testingonly"使用eg strcpy或use 将字符串复制到分配的位置,而不是更改指针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|
        +-+-+-+-+-+-+-+-+-+-+-+-+
Run Code Online (Sandbox Code Playgroud)

要么

char *test = strdup("testingonly");

        +-+-+-+-+-+-+-+-+-+-+-+-+
test--->|t|e|s|t|i|n|g|o|n|l|y|0|
        +-+-+-+-+-+-+-+-+-+-+-+-+
Run Code Online (Sandbox Code Playgroud)

  • +1感谢您解释它的努力. (6认同)

dic*_*rio 8

你已经回答了你的问题.从本质上讲,strcpy是复制字符串的合适方式.


Mat*_*Mat 5

第一个版本不会在堆栈上创建一个字符串,但是您在free分配后不允许使用它是正确的.字符串文字通常存储在内存的常量/只读部分中.赋值不复制任何东西,只是test指向那个内存区域.你不能释放它.您也无法修改该字符串.

你的第二段代码是正确和平常的.您可能还想查看strdup您的实现是否具有此功能.