I know that the variables allocated in this function stack become inaccessible when the function completes execution. However, vector types allocate their elements on the heap no matter how they are distributed. For example,
vector<int> A;
will allocate space for its elements on the heap instead of the stack.
My question is: suppose I have the following code:
int main(int argc, char *argv[]) { // initialize a vector vector<int> A = initVector(100000); // do something with the vector... return 0; } // initialize the vector vector<int> initVector(int size) { vector<int> A (size); // initialize the vector "on the stack" // fill the vector with a sequence of numbers... int counter = 0; for (vector<int>::iterator i = A.begin(); i != A.end(); i++) { (*i) = counter++; } return A; }
Will I have memory access issues when using vector A in the main function? I tried this several times and they all worked fine, but I'm afraid it might just be luck.
As I see it, vector A allocates its elements on the heap, but it has some "utility" parameters (possibly the size of the vector) allocated on the stack itself. Therefore, the use of a vector in the main function can lead to a memory access problem if these parameters are overwritten by another distribution. Any ideas?
alguru
source share