7
When we use any of the dynamic allocation functions in C (malloc, calloc, realloc, etc.), within a function that is called by main, will the memory remain allocated at the end of the execution of that function or will it automatically be out of focus? If memory remains allocated, how should I proceed to "handle" that previously allocated memory space outside the function?
Using the code below, for example, I need to use the chained list I created in add() in main
#include <stdio.h>
#include <stdlib.h>
struct celula{
int n;
struct celula *next;
};
typedef struct celula cel;
void adicionar();
int main ()
{
adicionar();
}
void adicionar()
{
cel *p, *p2, *aux;
int adc, x;
p = NULL;
printf("Deseja adicionar elementos na lista? \n 1- Sim \n 2- Nao \n");
scanf("%d", &adc);
if(adc == 1)
{
do
{
p2 = malloc(sizeof(cel));
printf("Digite o valor que deseja adicionar \n");
scanf("%d", &x);
p2->n = x;
p2->next = p;
p = p2;
printf("Deseja adicionar elementos na lista? \n 1- Sim \n 2- Nao \n");
scanf("%d", &adc);
}while(adc == 1);
}
aux = p;
while(aux != NULL)
{
printf("%d ", aux->n);
aux = aux->next;
}
}