简体   繁体   中英

Memory allocation mental map clarification

I want to clarify my mental map on memory allocation.

Lets suppose I have the following Array:

int arr [] = {1,2,3};

Lets suppose each integer will occupy 4 bytes in memory.

Such that the memory addresses of the integers could be :

HHH01 HHH05 HHH09

Will the memory chunk of arr be a superset of the memory chunks of each integer?

Strictly speaking, IIRC, the answer to your question is undefined and that's important because dipping into undefined behavior leads to some of the hardest and most obscure to track down bugs. Pointers and arrays don't necessarily have to map in memory in any specific fashion within the CPP standard. As long as they can properly perform the necessary arithmetic to find and de-reference to the proper elements, etc... anything beyond that should be considered safely abstracted away.

With that said... I think the answer to the question for most (if not all?) practical purposes is that your understanding is correct. If you were to cout << &(arr[0]);cout << &(arr[2]) you'd get the addresses you expect in any compiler that I've used and the amount of memory allocated will be the amount you'd expect. Doing cout << &(arr[3]) will even give you a valid address, though the data that's actually stored in arr[3] would be garbage. The only thing to be aware of is that different compilers and operating systems could provide different sizes and alignments of those elements. It's possible that if you were to check the size of int it could tell you that it's 2 bytes, but when you start looking at the addresses of the elements in an array printed out by a compiler they've got a 4-byte spacing.

In the end, while this can be interesting from an academic point of view... making actual use of it should be avoided at essentially all costs. If you start trying to manually access memory locations, it's likely to come back and bite you or whoever has to maintain your code down the line somewhere.

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