I use pointers as the function returns. Below is a simple snippet of code
The 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 a yield of 30 ..
But if you add one more function printhelloworld();
before adding as 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);
}
will not be more than 30, and this is undefined due to the release of the stack frame. I need to change my program as shown below usingmalloc()
int* add(int *a, int *b)
{
int* c = (int*)malloc(sizeof(int));
*c = *(a)+*(b);
return c;
}
It works.
But if I do not free the memory allocated in the heap, will it not remain forever? Should I use free()
as below?
free(c);
If I use free()
mainly, it c
does not fall within the scope, and it will not work, if I use "free" in the add, I get the result undefined again.
ASK:
free()
free(c);
#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);
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);
}