-1

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.

nitowa
  • 1,079
  • 2
  • 9
  • 21
  • 2
    It has long been said, that C gives you the ability to shoot yourself in the foot. I neither knows nor cares if you're a responsible gun owner. Basically, bounds-checking takes time. Time that is not available for other things. When programming a parking meter, it doesn't matter. When programming a game, sim or space-craft, such luxuries of time are unaffordable. – enhzflep Oct 22 '16 at 13:24
  • 2
    This is why, when programming C, you should leverage every compiler warning, static analyzer, and dynamic checker tool you can find. (ASAN, valgrind, splint, etc.) Unfortunately, because `myArray` here appears to be a stack variable, valgrind won't catch the bad access as you're actually just trashing the next variable on the stack. – Jonathon Reinhart Oct 22 '16 at 13:29
  • 1
    -fsanitize=address (clang and gcc) might help debugging bugs caused by memory errors. Also tools like valgrind can help. But like Jonathon said catching stack handling errors isn't possible for external tools. – Pauli Nieminen Oct 22 '16 at 13:41

2 Answers2

3

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.

kabanus
  • 24,623
  • 6
  • 41
  • 74
3

C does not do bounds checking on array accesses, and attempting to read or write past the end of an array leads to undefined behavior. Buffer overruns are a common malware exploit.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • +1 for mentioning buffer overruns. But I think you should elaborate on that a little to let OP know just how nasty they are. – Oskar Skog Oct 22 '16 at 13:45