Hi all,
I have a little problem with memory allocation.
At first, just have a look in my code:
Code:
#include <stdio.h>
#include <stdlib.h>
//Free memory
void end(int *a)
{
if(a != NULL)
{
free(a);
a = NULL;
}
}
//Fill random number into array
void fill(int *a, int n)
{
int i;
for ( i = 0; i < n; i++)
{
a[i] = rand()%19 -9;
}
}
//Display array
void display(int *a,int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
}
void main()
{
int *a = NULL;
int n = 10;//Element size
if ((a = calloc(n, sizeof(int))) == NULL)
{
printf("Memory can not allocate");
exit(-1);
}
fill(a,n);
display(a,n);
end(a);
}
You can see that it runs perfectly.
But if I make a little changes in fill function, my program will be crashed.
Code:
#include <stdio.h>
#include <stdlib.h>
//Free memory
void end(int *a)
{
if(a != NULL)
{
free(a);
a = NULL;
}
}
//Fill random number into array
void fill(int *a, int n)
{
int i;
if ((a = calloc(n, sizeof(int))) == NULL)
{
printf("Memory can not allocate");
exit(-1);
}
for ( i = 0; i < n; i++)
{
a[i] = rand()%19 -9;
}
}
//Display array
void display(int *a,int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
}
void main()
{
int *a = NULL;
int n = 10;//Element size
fill(a,n);
display(a,n);
end(a);
}
My questions is:
1. Why is my program crashed ?
2. I see that many programs which use the global variables to store pointer, so they can write initial function and de-allocated function separately. If I do not want to use global variables, how can I initiate and free memory by passing the pointer ?
Thank you.