assign memory using new

I assign memory to array of pointer as shown in code snippet below:

#include <iostream>
using namespace std;
#pragma pack(1)
int main()
{
int (*p)[4];
p = new int[3][4];
for(int i = 0; i < 4; i++) {
cout << p[i] << endl;
for(int j = 0; j < 3; j++)
p[i][j] = 0x11111111;
}
return 0;
}

As per this code it should assign 12 int(48 bytes on linux) of memory but when i see using gdb 16 int(64 bytes) allocated.

(gdb) print p
$1 = (int (*)[4]) 0x804fa10
(gdb) x/12xw 0x804fa10
0x804fa10: 0x11111111 0x11111111 0x11111111 0x00000000
0x804fa20: 0x11111111 0x11111111 0x11111111 0x00000000
0x804fa30: 0x11111111 0x11111111 0x11111111 0x00000000
(gdb)

Please can anyone explain why extra bytes are allocated here. Why this padding happens.
Chunk
A small range of memory that can be allocated (owned by the application), freed (owned by glibc), or combined with adjacent chunks into larger ranges. Note that a chunk is a wrapper around the block of memory that is given to the application.
...
Glibc's malloc is chunk-oriented. .... all chunks are multiples of 8 bytes ...

A chunk has a header (which has the size of he chunk and state flags) in addition to the payload area.

More information: https://sourceware.org/glibc/wiki/MallocInternals
1
2
p = new int[3][4]; //3 rows
for(int i = 0; i < 4; i++) {
you've swapped rows and columns.
So later you make an out-of-bounds access.

> but when i see using gdb 16 int(64 bytes) allocated.
¿may you explain that? ¿where do you see 16?
To ne555,
It seems you are right. I think i misunderstood the array of pointer declaration that is the reason i swapped rows and columns. I would like to discuss more about it here:

int (*p)[4];
As per me, p is an array of 4 elements and each element is again a pointer to int. I accessed each element using 'i' index from 0 to 3.

Please can you correct my understanding.
Last edited on
int (*p)[4];
p is a pointer. It points to arrays of 4 elements.

If it easier to understand, consider it like
1
2
3
4
5
6
typedef int array[4];

int main(){
   array *p; //a pointer to arrays of 4 elements
   p = new array[3]; //dynamically allocate 3 arrays.
}



If you wanted to declare an array of 4 pointers, then int *p[4]; (note the lack of parenthesis)
However, then you need to allocate the memory for each pointer, p[0], p[1], p[2], p[3].
Thanks a lot for the explanation. I got it.
Topic archived. No new replies allowed.