Paste number 52083: Closure in C.

Index of paste annotations: 1

Paste number 52083: Closure in C.
Pasted by: kehoea
When:4 years, 5 months ago
Share:Tweet this! | http://paste.lisp.org/+146R
Channel:None
Paste contents:
Raw Source | XML | Display As
#include <stdio.h>
#include <stdlib.h>

typedef int (*one_int_arg_funcptr)(int);

int beef;

int
addbeefton (int n)
{
  return beef + n;
}

one_int_arg_funcptr
addn (int n)
{
  size_t func_code_size = (char *)&addn - (char *)&addbeefton;
  one_int_arg_funcptr res = malloc (func_code_size);
  int *closed_n = malloc (sizeof (n));
  int **hackery = (int **)res;
  int i;

  *closed_n = n;
  memmove (res, (void *)addbeefton, func_code_size);

  for (i = 0;
       i < ((func_code_size + sizeof (int)) / sizeof (int));
       ++i)
    {
      if ((hackery[i] == &beef) != 0)
        {
          hackery[i] = closed_n;
          return res;
        }
    }

  return NULL;
}

int
main (void)
{
  one_int_arg_funcptr add_ten = addn (10);
  one_int_arg_funcptr add_four = addn (4);

  printf ("addn(10) gave %X\n", add_ten);
  printf ("addn(4) gave %X\n", add_four);  

  if (add_ten)
    printf ("calling add_ten with 5 gives %d\n",
            add_ten (5));

  if (add_four)
    printf ("calling add_four with 3 gives %d\n",
            add_four (3));

  return 0;
}

Annotations for this paste:

Annotation number 1: Version that triggered the compiler bug
Pasted by: kehoea
When:4 years, 5 months ago
Share:Tweet this! | http://paste.lisp.org/+146R/1
Paste contents:
Raw Source | Display As
#include <stdio.h>
#include <stdlib.h>

typedef int (*one_int_arg_funcptr)(int);

int beef;

int
addbeefton (int n)
{
  return beef + n;
}

one_int_arg_funcptr
addn (int n)
{
  size_t func_code_size = (char *)&addn - (char *)&addbeefton;
  one_int_arg_funcptr res = malloc (func_code_size);
  int *closed_n = malloc (sizeof (n));
  int **hackery = (int **)res;
  int i;

  *closed_n = n;
  memmove (res, (void *)addbeefton, func_code_size);

  for (i = 0;
       i < ((func_code_size + sizeof (int)) / sizeof (int));
       ++i)
    {
      if (hackery[i] == &beef)
        {
          hackery[i] = closed_n;
          return res;
        }
    }

  return NULL;
}

int
main (void)
{
  one_int_arg_funcptr add_ten = addn (10);
  one_int_arg_funcptr add_four = addn (4);

  printf ("addn(10) gave %X\n", add_ten);
  printf ("addn(4) gave %X\n", add_four);  

  if (add_ten)
    printf ("calling add_ten with 5 gives %d\n",
            add_ten (5));

  if (add_four)
    printf ("calling add_four with 3 gives %d\n",
            add_four (3));

  return 0;
}

Colorize as:
Show Line Numbers
Index of paste annotations: 1

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.