views:

149

answers:

3

Hello,

I am playing around with multidimensional array of unequal second dimension size. Lets assume that I need the following data structure:

[&ptr0]->[0][1][2][3][4][5][6][7][8][9]

[&ptr1]->[0][1][2]

[&ptr2]->[0][1][2][3][4]

int main()
{
 int *a[3];
 int *b;
 int i;

 a[0] = (int *)malloc(10 * sizeof(int));
 a[1] = (int *)malloc(2 * sizeof(int));
 a[2] = (int *)malloc(4 * sizeof(int));

 for(i=0; i<10; i++) a[0][i]=i;

 for(i=0; i<2; i++) a[1][i]=i;

 for(i=0; i<4; i++) a[2][i]=i;
}

I did some tests and it seems like I can store a value at a[1][3]. Does it mean that rows in my array are of equal size 10?

+1  A: 

It is undefined behavior of your code. You are accessing something that you don't own. It may work, it may not, but it is always wrong.

AraK
+1  A: 

No


There is lots of memory in your program used for I/O buffers, library data structures, the malloc system itself, command line arguments and environment, etc. (Some of those are on the stack.)

Yes, you can clobber things out of range.

Keep in mind that x[i] is the same thing as *(x + i). So, it's easy to calculate the address you referenced. It may overlay one of your data structures, it may overlay a part of your data structure that is a private field within malloc's mechanism, or it may overlay library data.

DigitalRoss
Thanks, now I understand how to calculate the exact address of accessed memory location
ashagi
"*(x + i)" to be exact, it should be *(x + i*sizeof(type pointed by x))
Phong
Yes, that's how its implemented, but I meant that literally, that is: in C `x[i]` can really be replaced by exactly `*(x + i)`. The multiplication by the size of the type is supplied by the compiler.
DigitalRoss
+3  A: 

No, The address a[1][3] does not "officially exist". It is a memory which is not define in your program and accessing it result in a undefined behavior.

It can lead to the following error:

  • Segmentation fault (access a restricted memory)
  • Used a memory already used by other variable (other allocation memory) (so possible overwrite)
  • It can be an uninitialized value (unsused memory address)
Phong
OK, so in a big run I could a get a runtime error. Thanks, that is exactly what I was unsure about.
ashagi
Pointer is not easy stuff, when you begin. I recommend you using Valgrind. It is a tools which can detect memory leak and the problem you mentioned in this post.
Phong