Created
May 23, 2017 16:19
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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