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?
Your assumption is not right.
c3does not point to the literal"abc". It points to the memory returned to bymalloc, which you copy in.Also,
c1andc3are both in automatic storage (on the stack). They are pointers in the function scope. The objectsc3points to is, however, in dynamic storage (the heap), butc3itself is not.A more correct graph is: