Hi CLCers,
I coded a function to allocate memory and i am passing a pointer to the
function. The code is compiling but throws error and closes while
executing. The program is as below:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *p;
void mem_fun(int *i);
Do not hide your function declarations within other functions.
Let us recapitulate: C passes arguments by value.
You have given no value to p, so making a copy of p for mem_fun
invokes undefined behaviour. From now on, anything can happen,
including your harddisk being formatted.
If you want to change something using a function, you have
to pass its _address_, not the object itself (which will only
copied but not changed).
Note: The address is also passed by value, but this value is
sufficient to do something.
printf("%d\n",*p);
getch();
This function is not defined in standard C.
return 0;
}
void mem_fun(int *i)
{
printf("%u\n",i);
The format specifier for pointers is %p.
If pointers and integers have different sizes, the above may
go wrong.
Better:
i = malloc(sizeof *i);
This works even if you change the type to i.
You forgot to check whether malloc() succeeded.
*i=10;
printf("%d\n",*i);
As you work on a copy of a pointer value which expires at the
end of the function, you have produced a memory leak.
}
Please help in understanding the problem. Advanced thanks.
Better:
#include<stdio.h>
#include<stdlib.h>
void mem_fun (int **i);
int main (void)
{
int *p = 0;
mem_fun(&p);
if (p)
printf("%p : %d\n", p, *p);
free(p);
getch();
return 0;
}
void mem_fun (int **i)
{
*i = malloc(sizeof **i);
if (*i)
**i = 10;
else {
fprintf(stderr, "mem alloc trouble\n");
exit(EXIT_FAILURE); /* Replace by _real_ error
** handling whenever possible */
}
}
As you see, I check _twice_ whether malloc() succeeded to be
on the safe side. This is because mem_fun() does not directly
tell me whether it was successful. You may consider returning
*i/int * to signal success or failure.
In addition, as malloc() is hidden within a function, free()
can be easily forgotten.
It is usually better to malloc() on the same "level" as you free()
or to provide companion functions to be called from the same
level performing malloc() and free().
Cheers
Michael