Access to External Allocated Space in C

Well, I always think that if I call the malloc function, I will assign a certain amount of memory, but I only realized that if I write:

int* a = (int*)malloc(sizeof(int) * 2); 

I can assign the value a[4] or any other index, although, in this case, I could only assign a[0] or a[1] . What is my concept error?

+4
source share
6 answers

When you write a[4] , it is the same as writing *(a + 4) . Since the compiler does not know how much memory is allocated at the address pointed to by a , it will gladly allow you to access the memory.

However, the memory located there can be anything - it can be another variable used by your program, part of the stack, or simply outside of your program. Accessing the external allocated space in this way is likely to lead (at best) to segmentation failure or (at worst) lead to a security hole by overwriting other parts of your program.

You are correct that you can only assign a[0] or a[1] safely , but the C compiler will allow you to assign external borders (because it knows nothing else),

It is impossible to do a[4] in your example.


Also, it is better not to give the malloc result - see this answer

+2
source

In C, there is no way to check for array overflow. You can continue writing outside the array until you start writing to an invalid address or read-only page, etc.

There are several tools available that make you immediately detect when you cross the boundary of an array. NJAMD is one such tool where it makes a memory location outside the bounds of a read-only array.

As with read-only memory access, it gives SIGSEGV. therefore, you can immediately detect array overflow.

+2
source

The term "error" means that C will protect you! C believes that you know what you are doing. You really can only use the index 0 or 1, but it wonโ€™t stop you using 4 (well, maybe the operating system).

+1
source

The reason you can do a[4] is because C does not perform any bounds checks. You can access the cell beyond the bounds of the array, and C will do this.

The problem is that this is a very bad practice and possibly a security hole. You should not do this, as this can lead to very bad and unforeseen consequences.

+1
source

Undefined behavior is simple - undefined. It may seem like this is โ€œworking,โ€ but it is not.

+1
source

To extend Keith's answer: you can overwrite memory on the heap, since C does not perform compilation or runtime checking. a [x] basically adds x * sizeof(x) to the "a" pointer. Pointer a points to the start of the malloced block.

+1
source

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


All Articles