Fernando Pérez
Fernando Pérez

Reputation: 119

How to intentionally preserve and harvest a dangling pointer in C++

I am writing an LLVM plugin. In it, I create a global array of pointers that take data along the flow of different functions in the program. When pointers take an address in a function scope, it is logical to assume that, once outside their scope, there is a risk that the content of the memory will be overwritten as the OS sees fit.

I would like to know if there is a way to make the content of the pointer unvariable (unless I find myself in the need to change it) through all scopes, of course, inside the program.

I thought that a flag like volatile would do the trick, but it seems like all this does is preserve its sequential position in comparison to non-volatile instructions.

Upvotes: 0

Views: 138

Answers (1)

Todd Christensen
Todd Christensen

Reputation: 1327

Most likely you need to copy the data.

You can actually mark memory unwritable, which won't allow anyone to write to it. However, if the pointer is on the stack or has been freed, this will probably have undesired consequences (namely, segfaults, and lots of them.) Additionally, it has to be done by page, e.g. in large chunks.

Remember, if I free a pointer, the data it pointed to can get reused later by another function. Even if I "promise" not to modify the data pointed to by the pointer, once it's freed... all bets are off. Someone else might allocate the same memory.

If you need to retain the data after free / it goes out of scope, you must copy it.

Upvotes: 1

Related Questions