我想知道为什么下面的代码不起作用
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
。请注意,如果可用内存不足,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|
+-+-+-+-+-+-+-+-+-+-+-+-+
关于c - 分配内存并在c中保存字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8600181/