If I were to initialize memory for a variable of four bytes, would I be able to point two two-byte variables to the memory stored for it? I'm trying to further understand memory management and theoreitcs.
An example of what I'm taking about:
int main() {
short* foo = malloc(4*(foo)); // sizeof(*foo)?
/*in which sizeof will return 2 so I could say
* malloc(20)
* so could I say malloc(2*sizeof(long))?
*/
}
Or are types generally declared adjacent to each other on the heap, I.e. a block is reserved for long, and a block is reserved for short typed variables?
Edit I forgot to include a question. If I were to declare two variables of type short next to each other (an array), could I safely point a long to the first item, an and access both via bitmap? Obviously this is mainly for theoretics, as I feel that there would be better, more obvious answers to problems.
Yes. C doesn't care about types when you allocate memory - it's just a block of memory as big as you've requested. It'll let you write in it, over it, under it ... until something bad happens!
If you want neighbouring values an array is a good way to go:
int *myAllocatedArray = (int*)calloc(2, sizeof(int));
myAllocatedArray[0] = 100;
myAllocatedArray[1] = 200;
calloc will initialize every byte to 0.
Yes it will work, because malloc takes integer arguments like: malloc(2*4), 4=sizeof(long), or anything like malloc(20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With