I recently discovered that C will allow me to do the following operation:
char* myArray[1];
myArray[0] = malloc(1024 * sizeof(char));
strcpy(myArray[0], "Hello");
myArray[1] = malloc(1024 * sizeof(char));
strcpy(myArray[1], "World");
//repeat ad absurdum
Effectively allowing me to fill myArray
as many pointers to data as I like, despite only explicitly requesting memory for one pointer inititally.
Why is this allowed?
Is this considered to be good practice or can this lead to unforseen consequences?
In my understanding the different indices of an array are allocated next to each other in memory, and since the address of myArray[1]
was never explicitly requested when the array was initialized, it could possibly be occupied by other data.