2

This question may not have any practical value, this is just out of curiosity. In C/C++ when you declare a variable like below:

int c;

variable c will have some garbage value in it. As per my understanding python doesn't have variables as in C/C++ but it has name-bindings with objects. So, according to me there is no way to get garbage as you always first create the object and then assign it a tag.

Garbage value actually is just whatever was stored at the location variable refers. But, I want to know if there is some way to get garbage values in python. In other words is there some way to access memory location without first initializing it. In my view it should not be possible and I appreciate it if this is by design. But I am just curious.

I am still learning both python and C++ and am not an expert so forgive me if this is a stupid question.

Pukki
  • 586
  • 1
  • 7
  • 18
  • You can do that in any language that allows you to use C/C++ based [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface). Python is one of such. – TNW Jan 23 '16 at 00:17

1 Answers1

1

This things usually depend on the interpreter that you are using. For example with CPython, you could do something like in this answer, or basically use C libraries like this other answer suggests.

to access memory location without first initializing it

Could be done with something like this,

from ctypes import string_at
from sys import getsizeof
from binascii import hexlify
# create a dummy object, just to get a memory location
a = 0x7fff
# and use it as a pivoting point to access other locations
offset = 100
print(hexlify(string_at(id(a)+offset, getsizeof(a))))

Needless to say this kind of things have its risks, but are an interesting experiment.

Community
  • 1
  • 1
Wakaru44
  • 423
  • 4
  • 14
  • I don't want the memory address of an object. That is pretty straight forward. I want to just get hold of some memory that is not assigned to any object. Both links in the answer deal with memory access after initialization. – Pukki Jan 23 '16 at 00:28
  • "to access memory location without first initializing it" you could just add positions after calculating id(a) in the example of the second link. – Wakaru44 Jan 23 '16 at 01:23
  • Thanks, I believe this is the kind of hack I was looking for. – Pukki Jan 23 '16 at 01:28