This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: malloc/free question..
- From: Ángel González <keisial at gmail dot com>
- To: I Rattan <ratta1i at cps dot cmich dot edu>
- Cc: gcc-help at gcc dot gnu dot org
- Date: Sat, 17 Mar 2012 01:04:52 +0100
- Subject: Re: malloc/free question..
- References: <4f63ca67.434bb60a.1711.6e81SMTPIN_ADDED@mx.google.com>
On 17/03/12 00:14, I Rattan wrote:
> Under Linux with gcc version 4.4.6 (Debian 4.4.6-11)
>
> The following code:
>
> int main(int argv, char** args)
> {
> int *arr;
> int n;
>
> n = 10000000;
>
> arr = (int *)malloc(4*n);
> free((void *)&arr);
> exit(0);
> }
>
> generates warning:
>
> err.c:14: warning: attempt to free a non-heap object 'arr'
>
> any ideas?
>
> -ishwar
arr is already a pointer. &arr is the storage of the pointer in the stack.
Thus the warning is perfectly valid. Your code is wrong.
You don't need to cast the free() parameter or the malloc() return value
in C.
I suspect malloc() isn't prototyped, and gcc is assuming malloc()
returns int.
That can have catastrophic results on systems such as 64 bit Linux.
You should #include <stdlib.h>, which provide malloc() and free()
prototypes
(as well as exit).