Home > Enterprise >  Is there a way to print all memory addresses a variable is stored in?
Is there a way to print all memory addresses a variable is stored in?

Time:09-29

I want to know if there is a way to print all the memory locations that say an int variable is stored in. Example:

#include <stdio.h>

int main()
{
        int x = 5;
        int *y = &x;
        printf("%p", (void*)y);
}

Example output: 0x100000000001

This will show the memory address that the first byte of x is stored in, but I want to see the memory address of each byte that it is stored in. Is there any way to do this? Or do I just assume the following memory place values since they're consecutive? i.e. the other memory locations of this int would be:

0x100000000002?

0x100000000003?

0x100000000004?

CodePudding user response:

If you know the variable type in the compilation time, you can use sizeof to determinate the variable memory size (in bytes) and then assume that the addresses range is from (char*)&var to (char*)&var sizeof(var) - 1.
If the variable is received as an allocated memory, you better use malloc_usable_size from <malloc.h> in order to get the variable size and then find the addresses range.

Note that usually operating-systems allocates virtual memory for processes.

CodePudding user response:

a way to print all the memory locations that say an int variable is stored in.

Sure. Form a loop [0...sizeof(int)).

int main() {
  int x = 5;
  void *y = &x;
  for (size_t i = 0; i < sizeof x; i  ) { 
    printf("%p\n", (void*)((char *)y   i));
  }
}
  • Related