Multidimensional array with unequal size of the second size using malloc ()

I play with a multidimensional array of uneven size of the second size. Suppose 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 have done some tests, and it seems that I can save the value in [1] [3]. Does this mean that the lines in my array are the same size 10?

+4
source share
3 answers

No, the address a [1] [3] does not officially exist. This is memory that is not defined in your program, and access to it leads to undefined behavior.

This may result in the following error:

  • Segmentation error (access to limited memory)
  • Uses memory already used by another variable (different allocation memory) (possibly overwritten)
  • This may be an uninitialized value (unsupported memory address)
+4
source

This is the undefined behavior of your code. You gain access to what you do not have. It may work, it may not be, but it is always wrong.

+1
source

Not


Your program uses a lot of memory for I / O buffers, library data structures, the malloc system itself, command line arguments and environment, etc. (Some of them are on the stack.)

Yes, you can knock things out of range.

Keep in mind that x[i] is the same as *(x + i) . Thus, it is easy to calculate the address you are referring to. It can overlay one of your data structures, it can overlay a part of your data structure, which is a private field in the malloc mechanism, or it can overlay library data.

+1
source

Source: https://habr.com/ru/post/1303424/


All Articles