M
MN
Hi all,
Suppose that I have the next program. My question is where to free the
pointer (ptr) dynamically allocated in function "test_free"?
Freeing "ptr" before return (), implies that "calc" will be lost, then
int the next function "add_data", "calc" will point to NULL pointer.
include <stdio.h>
#include <stdlib.h>
struct node
{
int x;
struct node* y;
};
struct node* test_free (struct node* calc, int a, int b);
struct node* add_data (struct node* calc, int c);
int main ()
{
struct node* calc = NULL;
int a = 5;
int b = 2;
int c = 3;
calc = test_free(calc, a, b);
printf("1- Value of x is %d\n", (int)calc -> x);
calc = add_data (calc, c);
printf("2- Value of x is %d\n", (int)calc -> x);
return (0);
}
struct node* test_free (struct node* calc, int a, int b)
{
struct node* ptr;
if (!ptr)
free(ptr);
ptr = (struct node*)malloc(sizeof(struct node));
ptr -> x = a*b;
ptr -> y = NULL;
calc = ptr;
free(ptr); //<---- here the problem
return (calc);
}
struct node* add_data (struct node* calc, int c)
{
calc -> x = (calc -> x)+ c;
return (calc);
}
After excuting I got
1- Value of x is 0
2- Value of x is 3
What I want is
1- Value of x is 10
2- Value of x is 13
Suppose that I have the next program. My question is where to free the
pointer (ptr) dynamically allocated in function "test_free"?
Freeing "ptr" before return (), implies that "calc" will be lost, then
int the next function "add_data", "calc" will point to NULL pointer.
include <stdio.h>
#include <stdlib.h>
struct node
{
int x;
struct node* y;
};
struct node* test_free (struct node* calc, int a, int b);
struct node* add_data (struct node* calc, int c);
int main ()
{
struct node* calc = NULL;
int a = 5;
int b = 2;
int c = 3;
calc = test_free(calc, a, b);
printf("1- Value of x is %d\n", (int)calc -> x);
calc = add_data (calc, c);
printf("2- Value of x is %d\n", (int)calc -> x);
return (0);
}
struct node* test_free (struct node* calc, int a, int b)
{
struct node* ptr;
if (!ptr)
free(ptr);
ptr = (struct node*)malloc(sizeof(struct node));
ptr -> x = a*b;
ptr -> y = NULL;
calc = ptr;
free(ptr); //<---- here the problem
return (calc);
}
struct node* add_data (struct node* calc, int c)
{
calc -> x = (calc -> x)+ c;
return (calc);
}
After excuting I got
1- Value of x is 0
2- Value of x is 3
What I want is
1- Value of x is 10
2- Value of x is 13