Home > Software design >  Allocate a specific memory address using pointers
Allocate a specific memory address using pointers

Time:10-13

Is it possible to allocate a memory that is next to an allocated memory?

for example,

there is a pointer that points to an allocated memory like this:

int a = 10;
int* ptr = &a;

so lets suppose &a is 0x0000004 it's next address according to its datatype will be 0x0000008. when I do

int* ptr2 = (ptr1   1);

ptr2 will be pointing to 0x0000008 address, but as it is unallocated memory, we cannot use it. Is there a way I can allocate that memory? I have tried doing.

int a = 10;
int* ptr = &a;
int* ptr2 = &(ptr[1]);
ptr2 = (int*) malloc(sizeof(int));

but obviously, this allocates a new memory and not 0x0000008. I have also tried using "new" keyword, but it is same as malloc(), so it doesn't as work as well.

As for the reason why I want to do this or where I want to use this. There is no specific reason. It is just an idea and I want to learn more about it.

I am using Windows 11 OS and Visual Studio 2022 IDE.

CodePudding user response:

You should familiarize yourself with the concept of memory layout and which data go where. Your int a variable will end up in the initialized data segment whereas the dynamic data you are trying to malloc will go into the heap, so they will have different addresses in memory. (By luck you might hit the heap from your initialized data, especially in the past, and even the stack segment, this is how buffer overflow attacks work, but now with all kind of randomization and memory protection mechanisms.) So, TL;DR, no you can't.

CodePudding user response:

When you do this (in a function)

int a = 10;
int *ptr = &a;

you're pointing to "stack memory". Stack memory is managed by the compiler, and is "allocated" when you declare variables.

int a = 10;
int b = 10;
int *ptr = &a;

Suppose &a is equal to 0x0000004. Depending on your compiler, &b may in fact be equal to 0x0000008, meaning ptr 1 may in fact be "allocated" already! Whether or not that's true, though, will vary based on compiler and platform. I wouldn't rely on it in real code, but it's fun to play around with.

If you want to allocate new memory on the stack, you can use alloca, which is kind of like malloc but for stack memory. Many stacks grow downwards, so you might be able to allocate ptr - 1 by calling alloca(sizeof(int)).

  • Related