# Call a method without calling it [closed]

Inspired by a now deleted StackOverflow question. Can you come up with a way to get a particular method executed, without explicitly calling it? The more indirect it is, the better.

Here's what I mean, exactly (C used just for exemplification, all languages accepted):

// Call this.
void the_function(void)
{
printf("Hi there!\n");
}

int main(int argc, char** argv)
{
the_function(); // NO! Bad! This is a direct call.
return 0;
}


Original question:

• +10471 ... nice – qwr Mar 1 '14 at 1:11
• I wonder how much rep you need to overflow stack overflow? – PyRulez Mar 1 '14 at 3:07
• Apparently this is a screencap from @Mysticial's account, seeing the avatar. Mysticial, could you please just click on your rep tab?!?!?! – Doorknob Mar 1 '14 at 3:30
• @Doorknob Why should he? Its all coming from one answer. – FDinoff Mar 1 '14 at 3:37
• @PyRulez Jon Skeet hasn't yet, so we're safe for now. – Cole Johnson Mar 1 '14 at 5:14

# Bash

If you want to have a good day, just type this as the first thing when you wake up. You will never feel sad after that.

trap 'echo Hello world' CHLD


## Dart

This calls nope() when calling the non-existing function yep().

import "dart:mirrors";

void main() {
new Nope().yep(text:"nope");
}

class Nope {

void noSuchMethod(Invocation invocation){
final Symbol s = new Symbol(invocation.namedArguments[#text]);
final InstanceMirror mirror = reflect(this);
mirror.invoke(s, []);
}

void nope() {
print("Nope!");
}
}


## ActionScript

In Actionscript 2 or 3 using the Flash GUI, place the function in a key frame:

// frame 2 labeled "func"
function hello() {
trace("Hi");
stop();
}

// frame 3
gotoAndPlay("func");


## Python

Python - Try and Except

 import sys
try:
print c
except NameError, SyntaxError:
print "Oh No!"


Not sure if this is allowed. If it's not, then I will delete it.

## Ruby

Probably it doesn't get enough attention, but in some languages we don't have methods/functions. Instead of that we have messages. Example:

send(:puts, 'Lol')


# C#

Garbage collection:

void Main()
{
var t = new Test();
t = null;
GC.Collect();
}

public class Test
{
public Test()
{
Console.WriteLine("Constructor called!");
}

~Test()
{
ImplicitCall();
}

private void ImplicitCall()
{
Console.WriteLine("ImplicitCall invoked...");
}
}


Inheritance:

This also uses the Garbage Collector but much more implicit.

void Main()
{
var d = new Derived();
}

class Base
{
void Foo()
{
Console.Write("Foo!");
}

~Base()
{
Foo();
}
}

class Derived : Base
{
}


# Java

Another Java Solution:

package callmethod;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
*
* @author aigon89
*/
public class CallMethod {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
CallMethod callMethod = new CallMethod();
// Calls helloWorld without calling it :O
Method m = callMethod.getClass().getMethod("helloWorld", null);
m.invoke(callMethod, null);
}

public void helloWorld(){
System.out.println("Hello World");
}
}


## Emacs Lisp

(defun hello (x) (insert "hello!"))

(let ((standard-output 'hello))
(print "hi"))


When ran it inserts "hello!" into the current buffer 7 times, then returns the string "hi"

# Java

Here are a few similar ideas:

### toString:

public class Call {
@Override
public String toString() {
System.out.println("hi");
return null;
}

public static void main(final String... args) {
String s = "foo" + new Call();
}
}


### hashCode:

import java.util.HashMap;

public class Call {
@Override
public int hashCode() {
System.out.println("hi");
return 0;
}

public static void main(final String... args) {
new HashMap<Call, String>().put(new Call(), "bar");
}
}


### finalize:

public class Call {
@Override
protected void finalize() {
System.out.println("hi");
}

public static void main(final String... args) {
new Call();
System.gc();
}
}


### writeReplace:

import java.io.*;

public class Call implements Serializable {
private Object writeReplace() {
System.out.println("hi");
return null;
}

public static void main(final String... args) throws IOException {
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(new Call());
}
}


Constructors, technically, are methods. So, I can just extend a class and the super constructor is automatically called without me having it "explicitly" called in my code.

Ex:

//SampleClass.java
class SampleClass {

public SampleClass() {
System.out.println("Constructor called");
}
}


//MainClass.java
public class MainClass extends SampleClass
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
new MainClass();
}
}


[Disclosure: Thought of it together with a friend of mine]

• There are ways to put both in one file... – SuperJedi224 Apr 12 '16 at 13:15

# C#

Why here is a wonderful program that compiles in safe mode, uses a horribly unsafe buffer overflow treats an array like a buffer, and abuses some quirks of the CLR. This works in x86 C#. A similar exploit can be done for x64 and is left as an exercise for the reader.

[StructLayout(LayoutKind.Explicit)]
class Union
{
public Union(byte[] bytes)
{
this.bytes = bytes;
}
[FieldOffset(0)]
[FieldOffset(0)]
}

class Program
{
static Union u = new Union(new byte[13]);
static Action a = ()=>Console.WriteLine("Somehow I was called?");
static void Main(string[] args)
{
var f = Marshal.GetDelegateForFunctionPointer((IntPtr)u.ints[12], typeof(Action)) as Action;
f();
}
}


The reason this works is that CLR allocates primitive struct type arrays as contiguous blocks. This is why you are allowed to cast a int[] to a uint[] via using an object first. The CLR however, will NOT allow you to normally cast a byte[] to an int[]. However, this Union class is COMPLETELY evil, and allows us to trick the CLR into treating the byte[] as an int[]. Basically we're back to pointer land now.

What's more fun is the CLR inserts a bound check on this access of the byte[] and still goes and does an access way out of the bounds of the array at this point. The executable code is located shortly after the accessible variable space. We then read it and then execute the function. This btw is horribly evil and if you do this in code I hate you.

# C#

Similar to my previous answer but even more insane and looking a lot more like standard csharp :)

namespace WTF
{
[System.Runtime.InteropServices.StructLayout(
System.Runtime.InteropServices.LayoutKind.Explicit)]
class Union
{
public Union(byte[] bytes)
{
this.bytes = bytes;
}
[System.Runtime.InteropServices.FieldOffset(0)]
[System.Runtime.InteropServices.FieldOffset(0)]
}

class Program
{
static Union u = new Union(new byte[133]);
static System.Action methodToCall = () => System.Console.WriteLine("I Should be called!");
static System.Action methodNotToCall = () => System.Console.WriteLine("But I was instead!");
static void Main(string[] args)
{
u.ints[42] = u.ints[50];
methodToCall();
}

}
}


While the previous code used pointers which is gross, this method is far worse. Here we rewrite the content of the content of the delegate's pointer to code with the content of method not to call by seemingly assigning a random empty array element to another element. As always don't try this at home kids.

# Javascript

!function(s){ alert(s) }("hi")


Just wondering if calling an anonymous function is call it without calling it.

# C

I guess this is rather silly, but doesn't this fit the criteria?

#include <stdio.h>

int main(void){
puts("Wow, nobody called me but I'm executing!");
}


# ForceLang with the Javascript module

cons js require njs
def wr io.write
set str "Hello, World!"
js function f(a){print("Hi");return null;}
js (function(){var io=Java.type("lang.ForceLang").parse("io");var mfield=Java.type("lang.FObj").class.getDeclaredField("fields");mfield.setAccessible(true);var map=mfield.get(io);map["put"](String.fromCharCode(119,114,105,116,101),new (Java.type("lang.Function"))(f))})()
wr str


# Ruby

Prints But who was call?.

begin
exit

def my_method
$>.puts "But who was call?" end rescue \ class <<$!
self
end

DATA.instance_eval do
system gets
send eval read << (read if seek $? >> 8) end end __END__ exit 13 begin  Alternatively... include Enumerable def each puts "But who was call?" end [*self]  ## GNU sed There is a beautiful way to do this in sed. In fact, when writing programs you could easily fall into this trap without realizing. I already had a post on Tips for golfing in sed documenting this feature. s/$/bar/
s/foo/&/
t foo_found()
b

:foo_found()
p


Run: sed -nf function_call.sed <<< ""

The foo_found() function is called when a search for foo is successful anywhere in the pattern space. The first line of code writes bar into the pattern space, previously empty. However, it will also indirectly, and surprisingly, help in calling the function foo_found()!

When the first line is commented out, the function is not called, as it was meant in the first place.

# PHP

$print=function(){print('Hello World!');}$print('Goodbye.');


in shrinked code, it is quite easy to miss the $ before the print. and without the variable name in the code, let´s obfuscate a bit: for($cc=64;++$cc<91;)${chr($cc);}=chr($cc);$p=$pr;$i=$in;
${"$p$i$t"}=function(){print('Hello World!');}
\$print('Goodbye.');