Re: C + Malloc
From: Serge Paccalin (sp_at_mailclub.no.spam.net.invalid)
Date: 10/14/04
- Next message: Daniel Vallstrom: "Floating-point bit hacking: iterated nextafter() without loop?"
- Previous message: Richard Bos: "Re: How to retrieve the name of the file from a FILE *"
- In reply to: lasek: "C + Malloc"
- Next in thread: S.Tobias: "Re: C + Malloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 14 Oct 2004 12:12:30 +0200
Le jeudi 14 octobre 2004 à 11:45, lasek a écrit dans comp.lang.c :
> Hi...i'm writing from Rome...and i don't know english very well so...
> Only simple question, which is the difference between those two parts of
> code.
The second piece of code has a bug called a memory leak.
> [FIRST]
> int *pInt=NULL;
> int iVar=10;
> pInt=&iVar;
>
> [SECOND]
> int *pInt=NULL;
> int iVar=10;
> pInt=(int*)malloc(1*sizeof(int));
> pInt=&iVar;
>
> I really need to allocate memory before assign an address to a pointer
> variable?.
Yes but calling malloc() is only one way of allocating memory. Defining
a variable is another way.
[FIRST]
int *pInt=NULL;
int iVar=10;
pInt=&iVar;
You allocated a small piece of memory when you defined iVar. Then you
put the address of that memory into pInt. This code is correct. Note
that iVar will go away when you leave the current block of code.
[SECOND]
int *pInt=NULL;
int iVar=10;
pInt=(int*)malloc(1*sizeof(int));
pInt=&iVar;
You allocated a small piece of memory when you defined iVar. Then you
dynamically allocated another small piece of memory by calling malloc()
and put its address into pInt. Finally you put the address of iVar into
pInt *and lost the only copy of the address of the dynamically allocated
memory; you need to free it by calling free(), but now you can't because
you don't have its address anymore...
> Thus because i know that declaration not allocate memory for pointer
> variable.
Each time you define a variable, you allocate memory for the variable.
If it's a pointer, you allocate memory for the pointer itself but not
the memory you want to point to.
-- ___________ 14/10/2004 12:02:35 _/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net \ \_L_) Il faut donc que les hommes commencent -'(__) par n'être pas fanatiques pour mériter _/___(_) la tolérance. -- Voltaire, 1763
- Next message: Daniel Vallstrom: "Floating-point bit hacking: iterated nextafter() without loop?"
- Previous message: Richard Bos: "Re: How to retrieve the name of the file from a FILE *"
- In reply to: lasek: "C + Malloc"
- Next in thread: S.Tobias: "Re: C + Malloc"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|