【发布时间】:2020-12-10 13:27:25
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
char* get_string(){
// char* pointer = malloc(sizeof(char)*10);
char* pointer = "string";
printf("%s\n",pointer);
return pointer;
}
int main(){
// char* got = malloc(sizeof(char)*10);
char* got = get_string();
printf("%s\n",got);
// free(got);
}
这段代码在测试中没有给出警告。 但我的问题是: 对于以下几行代码,
char* got = malloc(sizeof(char)*10);
got = get_string();
为什么这里不需要malloc?
为什么不需要分配内存来存储函数返回的指针?
我现在有点困惑。
谢谢。
【问题讨论】:
-
char* pointer = "string";已经为pointer分配了内存,而pointer指向只读内容,可以返回并传递,但不能修改其内容 -
您确实有存储指针的位置。变量
got在堆栈上有足够的空间来存储一个指针。它与int x = 5没有什么不同,其中提供了空间来存储整数。 -
请注意,
char *got = malloc(...); got = get_string()是内存泄漏,因为您丢失了 malloc 返回的值。就像int x = 5; x = 7一样,5 丢失了。 -
请注意复制字符串(
strcpy()等)和分配指针之间的区别。你不能直接分配数组。
标签: c pointers dynamic-memory-allocation