Skip to content

Instantly share code, notes, and snippets.

@shivabhusal
Created May 23, 2017 16:19
Show Gist options
  • Select an option

  • Save shivabhusal/c82b9560bb0119f325baf6f9fe681dae to your computer and use it in GitHub Desktop.

Select an option

Save shivabhusal/c82b9560bb0119f325baf6f9fe681dae to your computer and use it in GitHub Desktop.
Demonstrate how we can store local vars to heap using `calloc`, `malloc` so that we can return the references to the caller.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int* getSum(int a, int b){
/* Local var stored in `heap` instead of `stack` */
int* sum = malloc(sizeof(int));
*sum = a + b;
return sum;
}
void main(){
/* Writing assertions to test the result */
assert(*getSum(12, 12) == 24);
assert(*getSum( 0, 12) == 12);
assert(*getSum(-1, 12) == 11);
assert(*getSum(-3, 12) == 9);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment