C语言:动态分配含非动态元素的结构体的内存位置及释放问题
Great question—let's walk through this line by line to clear up your confusion.
1. Is the struct member
c allocated on the heap? Absolutely yes. Here's why:
- When you call
malloc(sizeof(A)), you're requesting a block of memory on the heap that's exactly the size of yourAstruct. In this case, sinceAonly contains anintmemberc, the block is the size of a singleint. - The pointer
astores the address of this heap-allocated block. When you accessa->c, you're directly referencing the portion of that heap block reserved for thecmember.
To put it simply: the entire struct (and all its members) lives in the heap memory you allocated with malloc. If you had declared a struct on the stack like A a_stack;, then a_stack.c would live on the stack—but that's not what's happening here.
2. What happens to
c's memory when we call free(a)? When you call free(a), you're telling the operating system's memory manager that the heap block pointed to by a is no longer needed and can be reused for future allocations. Here's what that means for c:
- The memory that held
cis marked as available by the memory manager, but it's not automatically erased. The value2might still be present in that memory location for a while, but this is just "garbage" data—your program has no right to access it anymore. - Accessing
a->cafterfree(a)is undefined behavior. Your program could crash, return a random value, or behave unpredictably—never do this. - After
free(a), the pointeraitself still holds the old address of the freed block (this is called a "dangling pointer"). It's a good practice to seta = NULLimmediately after freeing to avoid accidental access to freed memory.
内容的提问来源于stack exchange,提问作者giudaballerino
相关产品推荐
相关产品推荐

