[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Heap, Arrays and Structures
From: |
R Karthick |
Subject: |
Heap, Arrays and Structures |
Date: |
Tue, 4 Dec 2007 21:02:53 -0800 (PST) |
User-agent: |
G2/1.0 |
Hi,
This might be a very primitive question. But I want to be clear about
the allocation mechanism adopted by C++.
This program uses a dynamically allocated structure and array.
<code>
extern "C" void* sbrk( ssize_t incr );
struct foo_structure
{
char foo_char[50000];
};
int main()
{
int d1, d2, d3;
int *foo_int;
foo_int = new int[50000];
foo_structure *foo = new foo_structure;
printf("LOCAL VARIABLES \n");
printf("Address of &d1: %p\n", &d1);
printf("Address of &d2: %p\n", &d2);
printf("Address of &d3: %p\n\n", &d3);
printf("HeapEnd: %p\n\n", (unsigned int *) sbrk(0));
printf("ARRAY \n");
printf("Address of &foo_int: %p\n", foo_int);
printf("Address of &foo_int[0]: %p\n", &foo_int[0]);
printf("Address of &foo_int[1]: %p\n", &foo_int[1]);
printf("...\n");
printf("Address of &foo_int[49999]: %p\n\n", &foo_int[49999]);
printf("STRUCTURE \n");
printf("Address of foo_struct: %p\n", foo);
printf("Address of &foo: %p\n", &foo);
printf("Address of &foo->foo_char[0]: %p\n", &foo->foo_char[0]);
printf("Address of &foo->foo_char[1]: %p\n", &foo->foo_char[1]);
printf("...\n");
printf("Address of &foo->foo_char[49999]: %p\n\n", &foo-
>foo_char[49999]);
}
</code>
The output is
<output>
LOCAL VARIABLES
Address of &d1: 0xbf9d30f8
Address of &d2: 0xbf9d30f4
Address of &d3: 0xbf9d30f0
HeapEnd: 0x8077000
ARRAY
Address of &foo_int: 0xb7c70008
Address of &foo_int[0]: 0xb7c70008
Address of &foo_int[1]: 0xb7c7000c
...
Address of &foo_int[49999]: 0xb7ca0d44
STRUCTURE
Address of foo_struct: 0x804a008
Address of &foo: 0xbf9d30fc
Address of &foo->foo_char[0]: 0x804a008
Address of &foo->foo_char[1]: 0x804a009
...
Address of &foo->foo_char[49999]: 0x8056357
</output>
I understand that local variables go into the stack in the 0xb9
address range. I can see that "STRUCTURE", foo_struct is getting
allocated in the heap. (Note: heap end is, 0x8077000). I am confused
about the allocation of the "ARRAY", foo_int. I was hoping as the
array is also initialized using "new" it will take some memory from
the heap address range. I would like to know where exactly the array
is allocated. (0xb7c70008 ... ).
Btw, I am running GCC 4.1.3 version under, X86 box running Ubuntu.
Thanks!
-Karthick R
- Heap, Arrays and Structures,
R Karthick <=