我想知道为什么下面的代码不能工作
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);
}
发布于 2011-12-22 06:51:54
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.
您需要使用例如strcpy
或strdup
将字符串"testingonly"
复制到分配的位置,而不是更改指针test
。请注意,如果内存不足,像malloc
和strdup
这样的函数将返回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|
+-+-+-+-+-+-+-+-+-+-+-+-+
发布于 2011-12-22 06:36:31
你已经回答了你的问题。从本质上讲,strcpy是复制字符串的合适方式。
发布于 2011-12-22 06:37:53
第一个版本不会在堆栈上创建字符串,但是您是正确的,在赋值之后不允许free
它。字符串文字通常存储在内存的常量/只读部分中。赋值不会复制任何内容,只是让test
指向该内存区域。你不能释放它。您也不能修改该字符串。
你的第二段代码是正确的,而且是正常的。如果您的实现具有strdup
,那么您可能还想研究一下它。
https://stackoverflow.com/questions/8600181
复制