<分区>
Possible Duplicate:
C Array Instantiation - Stack or Heap Allocation?
当动态分配一个包含 char 指针的结构时,实际的 char 指针会发生什么?它存储在哪里?
一旦结构被释放,char 指针是否也随之释放?
例如考虑以下结构:
struct mix
{
int a;
float b;
char *s;
};
typedef struct mix mix;
然后是下面为其分配内存的代码:
int main()
{
mix *ptr = (mix*)malloc(sizeof(mix));
ptr->a = 3;
ptr->b = 4.5f;
ptr->s = "Hi, there, I'm just a really long string.";
free(ptr);
return 0;
}
*s
是否在堆栈上分配,然后与 *ptr
一起释放?我可以想象它确实是在堆栈上分配的,因为它不是以任何方式动态分配的(除非 malloc 具有我不知道的某些功能)。我猜想 *s
的“超出范围”将是在释放 *ptr
的时候。还是我完全错了? :)
非常感谢!