I am using Pointers as function returns ..below is a simple piece of code
main function:
void main()
{
int a = 10, b = 20;
int *ptr;
ptr = add(&a, &b);
printf("sum of a and b is %d\n", *ptr);
}
add function:
int* add(int *a, int *b)
{
int c;
c = *(a)+*(b);
return &c;
}
This works correctly and gives me output 30..
But if you add one more function printhelloworld(); before add like below
void main()
{
int a = 10, b = 20;
int *ptr;
ptr = add(&a, &b);
printhelloworld();--this just prints hello world
printf("sum of a and b is %d\n", *ptr);
}
output will not be 30 any more and it is undefined due to stack frame getting freed..so I have to modify my program like below using malloc()
int* add(int *a, int *b)
{
int* c = (int*)malloc(sizeof(int));
*c = *(a)+*(b);
return c;
}
This works.
But if I don't free memory allocated in heap, won't it stay forever ? Should I not use free() like below ?
free(c);
If I use free() in main,c is not in scope and it won't work, if I use 'free` in add, again I will get undefined result.
ASK:
What is the correct way to use free() in my case
free(C);
Total program for repro
#include<stdio.h>
#include<stdlib.h>
void printhelloworld()
{
printf("hello world\n");
}
int* add(int *a, int *b)
{
int* c = (int*)malloc(sizeof(int));
*c = *(a)+*(b);
//free(c);
return c;
}
int main()
{
int a = 10, b = 20;
int *ptr;
ptr =(int*) malloc(sizeof(int));
ptr = add(&a, &b);
printhelloworld();
printf("sum of a and b is %d\n", *ptr);
}