Reputation: 1170
Where are pointer variables and functions located?
Upvotes: 0
Views: 81
Reputation: 213375
Functions are in .text
section.
Pointers are wherever: local pointers on stack, global/static points in .bss
, etc.
Yes, an automatic (on stack) pointer could point anywhere (or nowhere at all):
void foo() {
char *p = NULL; // this pointer points nowhere
const char *q = "hello"; // points to read-only constant
char buf[1], *r = buf; // r points to stack
}
There is no difference between pointers and other kinds of variables; just as buf
above ends when foo()
returns, so do p
, q
and r
.
Also note that that lifetime of the pointer, and the lifetime of the entity it points at have nothing to do with each other. A pointer may have shorter, same, or longer lifetime than the pointed-at entity (and this is a rich source of bugs in C
and C++
). Some examples:
int *gp1, *gp2, *gp3;
void foo() {
int j;
int *lp1, *lp2, *lp3;
gp1 = lp1 = &j; // both global 'gp1' and local 'lp1' point to local 'j'
gp2 = lp2 = new int; // 'gp2' and 'lp2' point to dynamically allocated
// anonymous 'int'
if (true) {
int j2;
gp3 = lp3 = &j2;
}
// 'gp3' and 'lp3' are "dangling" -- point to 'j2' which no longer exists.
}
Once foo
returns, gp1
, gp2
and gp3
all still exist, but only gp2
points to valid memory.
Upvotes: 4
Reputation: 13346
Pointer variables have not different to data variables. And functions are your real program, function name will be converted to an internal symbol after compiled used to locate an address in memory where the function body begins and function body will be compiled to assembles, machine code eventually.
=================================================================================
[Edit for the Second Question]
As I pointed out, pointer variables have no different to data variables, including the storage and lifetime. e.g. This is an example .cpp file
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int I_m_data = 10;
int *I_m_global;
int *I_m_initialized = &I_m_data;
int main(){
int *I_m_local = NULL;
int **dynamic_allocated = (int **)malloc(sizeof(int *));
free(dynamic_allocated);
}
Here, I_m_global
is in .bss section, I_m_initialized
is in .data section, I_m_local
is on stack, and pointer pointed by dynamic_allocated
is on heap while dynamic_allocated
itself is on stack.
Besides, I_m_global
and I_m_initialized
have global lifetime; I_m_local
and dynamic_allocated
cannot be indexed out of main
. Remember free heap space pointed by dynamic_allocated
manually in case of memory leak.
Good luck!
Upvotes: 1