nitowa nitowa - 1 month ago 14
C Question

Writing beyond the end of an array in C

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.

Answer

C is a very unsafe language. You can do usually anything you want, and definitely ruin memory by doing what you did. Often in simple programs you won't notice the effects, but it quickly becomes evident.

In short - it's allowed but dangerous and shouldn't be done.

When programming in c, you have to check yourself at every line.