void foo()
{
char *c1 = "abc";
static char *c2 = "abc";
char *c3 = malloc(10);
strcpy(c3, "abc");
}
In foo
, I assume:
c1
is a local pointer, so it should be on the stack;
c2
is a static pointer, it should be on the heap;
c3
is on the heap.
According to my assumption, I draw a graph about the pointers and the string literal they're pointing,
stack rodata heap
| | | | | |
| c1 |------>| "abc" |<--------| c2 |
| .. | | | \ | .. |
| | | | `------| c3 |
| | | | | |
My assumption and graph right?
Still, I don't quite understand why should c3
be on the heap? c3
is just a char *
, just pointing to an address (located on the heap) doesn't make c3
on the heap, right?
A static pointer can be used to implement a function that always returns the same buffer to the program. This can be helpful in serial communication.
All variables allocated by malloc (or new in C++) is stored in heap memory. When malloc is called, the pointer that returns from malloc will always be a pointer to “heap memory”. All variables used as local variables – for example, when you just do int i = 0; – is stored on a function's stack.
Return Valuemalloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
The malloc( ) (memory allocate) function can be used to dynamically allocate an area of memory to be used at run time. Heap memory is used for these variables that use malloc( ).
Your assumption is not right. c3
does not point to the literal "abc"
. It points to the memory returned to by malloc
, which you copy in.
Also, c1
and c3
are both in automatic storage (on the stack). They are pointers in the function scope. The objects c3
points to is, however, in dynamic storage (the heap), but c3
itself is not.
A more correct graph is:
stack rodata heap global
| | | | | | | |
| c1 |------>| "abc" |<--------------------| c2 |
| c3 |------------------------>| "abc" |
| | | | | |
| | | | | |
The actual variable, c3
is located on the stack, because it's a local variable. However, the data that c3
points to will be on the heap, because the pointer was created with malloc
.
Note that you must free what c3
points to before your function returns, or you will have memory leaking in your application, which is never a good idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With