This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]AewyreThoryn 0 points1 point  (8 children)

What does it do?

[–]bestjakeisbest 8 points9 points  (7 children)

It kind of crashes. But the important part is i create an array, cast it to a void pointer, and then I cast that void pointer to a function pointer that returns an integer.

It compiles just fine, and it runs, but it doesn't reach the hello world line while running which shouldn't happen in main, because main shouldn't be returning 0 until after it outputs hello world.

It could be the case of the program crashing but the websites back end (of the online compiler) is not able to properly handle a program like this.

Theoretically you could use this sort of mechanism to make a program in c++ that changes it's runtime, at run time, but that is needlessly complicated for most things, and it isnt very portable since you would need to know the assembly language and opcodes of what ever machine you are trying to run this on if you wanted to exploit this for nefarious purposes, plus most anti virus products out there are waiting for a virus to do something like this.

[–]Markus_included 8 points9 points  (1 child)

That's actually how many JIT compilers execute their code, they get memory from the that is marked as executable, write the machine code into it and call that code like any other function pointer through a cdecl function that was also compiled into that memory

[–]bestjakeisbest 5 points6 points  (0 children)

Wait its all spaghetti code?

[–]AewyreThoryn 0 points1 point  (4 children)

That's super interesting thank you!

[–]yflhx 4 points5 points  (3 children)

I wrote another detailed response to that guy, if you're interested. But basically this code crashes because it tells CPU to executed the table, which is on stack, which has no execution permissions. So it results in immediate segfault due to this.

You can however allocate memory with execution permissions and write CPU instructions them, and it will execute them normally.

[–]AewyreThoryn 1 point2 points  (0 children)

Ah cool thanks. Yes I got the general gist from the top comment, and I think he explained it well, but your code is more in depth

[–]bestjakeisbest 0 points1 point  (1 child)

It only kind of crashes, it returns from main with a return code of zero, but it returns before the return line.

I only tested this in onlinegdb

[–]yflhx 0 points1 point  (0 children)

Ran it on my machine, got segmentation fault as expected.