DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
 
zhu48 profile image
Zuodian Hu

The NOPs don't actually give you any memory. Those NOPs are wherever the executable image was loaded in memory, and the variable yep is on the stack. Assuming your standard C memory model.

Thread Thread
 
theoutlander profile image
Nick Karnik

I misread the post on the phone, but I see what the code is doing. Although, I'm not sure what assigning to NOP does?

Thread Thread
 
cathodion profile image
Dustin King

C memory layout:

C memory layout (source)

The function code itself is in the text segment. The variables for a particular invocation of the function are on the stack. Padding out the function with NOP creates space within the function, which I'm using as a variable. Basically I'm interpreting the "working memory" part of the post to mean "variables allocated on the stack". Now that I think of it, what I'm doing is basically a static variable, which (according to the link) C puts in the initialized data segment if you do it the right way, but then it would legitimately be a variable so I'd lose.

It's probably not a legit way to do things (and might be impossible if the text segment is read-only as the link says it might be), but people had already posted the legit ways.

Thread Thread
 
theoutlander profile image
Nick Karnik

Thanks for that explanation. It's been a while since I've written C/C++, but this approach makes sense. I love the thought process of cleverly using that available memory, even if it doesn't work out. 👏👏👏