SeaNick
SeaNick

Reputation: 511

Safely Use Explicit Address Assignment

Is there a best practice of any type in regards to using an explicit number for a pointer address safely? By that I mean the following example:

#define BASE_ADDRESS  0x10000

typedef struct my_var_list
{
   int var1;
   int var2;
} my_function_list;

my_var_list *MyVars;
MyVars = BASE_ADDRESS;    // Set the address of MyVars to be 0x10000

This may demonstrate some ignorance on my part, but how can you guarantee that 0x10000 is not being used by something else at that time and you aren't causing memory corruption? If you can't assume that, is there any safe way of hard defining an address to use?

Upvotes: 0

Views: 109

Answers (2)

Drew McGowen
Drew McGowen

Reputation: 11706

If you're running under Windows, the VirtualAlloc function allows you to specified a recommended base address. If the requested region is free, VirtualAlloc will use that. If, however, the region is in use, VirtualAlloc will select a different base address.

For linux (and maybe unix), you can use the mmap function the same way - it'll try your given address first before picking a different one.

Upvotes: 1

pm100
pm100

Reputation: 50210

the assumption is that if you KNOW its 0x10000 then you also know when that is true. Typically this is for hardware stuff (I know io port 5 is at 0x10000) or low level OS kernel (boot image is loaded at 0x10000 by another part of kernel). If you arent writing either of those things then you shouldnt be doing hard coded addresses

Upvotes: 5

Related Questions