简体   繁体   中英

accessing unallocated memory while sort from algorithm stl c++

while I was going through stl today, I came across a situation where to sort my dynamically allocated array from arr[0],,..arr[n-1] . I was using command

#include<algorithm>
.
.
int *arr = new int[n]();
//loop to take user input for each arr[i]
sort(&arr[0],&arr[n]) 

The above command was sorting the array without any error, even if I have allocated memory up to arr[n-1] .

The below command was sorting upto n-1th element.

#include<algorithm>
.
.
int *arr = new int[n]();
//loop to take user input for each arr[i]
sort(&arr[0],&arr[n-1]) 

How was ' &arr[n] ' working in the 1st code snippet.

STL algorithms use "half-open" ranges. That means it includes the first element and works up to--but not including--the last element. Given:

std::sort(&arr[0], &arr[n]);

The sort function will sort the elements from 0 to n - 1 . It will never try to look in arr[n] .

In C and C++, it's legal to create a pointer to the first element beyond the end of an array, but you cannot dereference that pointer.

When you changed the call to:

std::sort(&arr[0], &arr[n-1]);

you introduced a bug, since this will ignore the last element in the array when sorting.

Using half-open ranges (or intervals) is pretty natural given that arrays are indexed from 0.

Arrays are 0 indexed in C++. If you have n elements then the first index is 0 and the last is n-1 .

It was working because it's undefined behavior. It can do anything. Often what happens is you just overwrite some variable on the stack with nonsense. If it's the right variable this can allow someone to overload that buffer with targeted nonsense and cause code to be executed. It's called a "buffer overrun" and you need to avoid them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM