1

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.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 2
    The only way to guarantee that memory will be allocated adjacently this way would be using an array (e.g. `int a[2];`) or a `struct` (e.g. `struct {int a, b} ab;`). Also `new` is C++ not C and this question is tagged [tag:c]. – user16217248 Oct 13 '22 at 05:09
  • Yes True . But I don't want to do it that way. I want to allocate a memory of my choice. Then what will be the way. Keeping in mind the ambiguity etc. that can be caused. and also that the next consecutive memory might also be allocated to a different variable. – Huzaifa Malik Oct 13 '22 at 05:13
  • 1
    Well then, I cannot speak for Windows 11, but as far as standard C is concerned, the answer is **you can't**. – user16217248 Oct 13 '22 at 05:15
  • Does this answer your question? [Can I Allocate a specific memory address using pointers in c++?](https://stackoverflow.com/questions/10364582/can-i-allocate-a-specific-memory-address-using-pointers-in-c) – Iłya Bursov Oct 13 '22 at 05:16
  • But if I can allocate memory dynamically, (which gives a random memory to me) why can I not specify which memory to allocate for me? It should be possible. I can edit values on an unallocated memory. But I cannot allocate that memory. why? – Huzaifa Malik Oct 13 '22 at 05:18
  • @Iłya Bursov Actually it does'nt. It sayd VirtualAlloc(), which is used I other situations. And other ways donot allocate memory. – Huzaifa Malik Oct 13 '22 at 05:19
  • @HuzaifaMalik memory is managed by OS, not by C, so you cannot do it in pure C, you have to use OS functions for that and VirtualAlloc allows you to allocate adjacent memory block (because it allows you to allocate at any address), so it does answer your question – Iłya Bursov Oct 13 '22 at 05:22
  • There is nothing in the C standard that enables this. I doubt any main stream implementations can do this. I will say the answer is no – Support Ukraine Oct 13 '22 at 05:43
  • @user16217248 Even with a struct there is no guarantee.... – Support Ukraine Oct 13 '22 at 05:49
  • @SupportUkraine How so? – user16217248 Oct 13 '22 at 05:59
  • @user16217248 The C standard allows padding in structs so you can't know whether there will be padding between two ints in a struct – Support Ukraine Oct 13 '22 at 06:01
  • How would you know whether there is even any memory available at that location? You might tell us what you are actually trying to achieve. Do you want to access some hardware registers at a given address? Do you want to access same memory area from different processes? BTW: You might be able to modify values at unallocated memory but that does not make it legal for you. – Gerhardh Oct 13 '22 at 06:01
  • If you need to add stuff to same allocation, in C, you can use `realloc()` to make the allocation bigger. It may move the allocation and is not compatible with C++ `new`, of course (in C++, you could just use `std::vector` for the buffer instead). – hyde Oct 13 '22 at 06:14
  • @SupportUkraine What kind of silly compiler would insert padding between 2 `int` fields? – user16217248 Oct 15 '22 at 02:52
  • @user16217248 The point is not whether a silly compiler would insert padding. The point is that the C standard allows it and therefore we can't say for sure that it wont happen. Would there ever be a case where it could make sense to do it.... yes, to avoid false sharing in a multi-threaded app.... but that is not something a "silly" compiler would be able to figure out. That would require a very smart compiler. – Support Ukraine Oct 15 '22 at 05:25
  • 1
    @SupportUkraine So the only standard way is array then, because packed structs rely on compiler specific features (e.g. `__attribute__((packed))`) – user16217248 Oct 15 '22 at 05:27

4 Answers4

2

The C standard does not provide any method to allocate memory at a specific address.

“Allocating memory” is just making arrangements for the memory not to be used for any other purpose. To provide an allocation service, the C implementation has some plan about how to use memory. Some space is planned for constants, some is planned for static objects (variables defined outside of functions or with static), some is planned for automatic objects, some is planned for instructions of the program, and so on. Some region of the address space is planned for be used with malloc. The library software that implements malloc and related routines keeps a database of what portions of that region of address space are available for allocation. When you call malloc, they choose some space in that region and update that database to indicate that space is no longer available.

To give you space adjacent to an existing variable, the C implementation would have to have some way of recording that that space is not available for any other use. And it would have to ensure that space is not already in use for something else. In typical C implementations, there is simply no provision made for that. All the parts of space planned for things other than dynamic allocation have their own plans about how they are used, and there is no provision for carving out any pieces of them for dynamic allocation.

In special-purpose environments, a C program may be written to manage some or all of its own address space, or the operating system or environment may provide support for this. Even in such cases, the memory is generally managed by arrangements made during system design and building of the software, not during program execution.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

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)).

  • true, but it is also possible that the next memory is not allocated. I accept the fact that the next consecutive memory might already be allocated. but i am asking in a hypothetical situation that suppose it is not allocated. – Huzaifa Malik Oct 13 '22 at 05:09
  • Sure. I suppose if you're specifically asking "can I allocate a specific stack address?" then the answer is probably no. There is [alloca](https://man7.org/linux/man-pages/man3/alloca.3.html), 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))`. – Nigel Baillie Oct 13 '22 at 05:22
1

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.

Serguei
  • 236
  • 3
  • 12
1

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

The answer is: No

There is nothing in the C standard that describes how variables are placed in memory. It all depends on the implementation being used so you can't write portable C code controlling how variables are placed in memory.

You can write your own memory allocator which can give the user control over allocation within the memory owned by your memory allocator but it can't be made to work together with variables with automatic/static storage duration like int a;

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63