Re: C + Malloc

From: S.Tobias (sNOiSPAMt_at_amu.edu.pl)
Date: 10/14/04


Date: 14 Oct 2004 10:20:00 GMT

lasek <claudio.rossetti@acrm.it> wrote:
> Only simple question, which is the difference between those two parts of
> code.

> [FIRST]
> int *pInt=NULL;
> int iVar=10;
This is a definition, so iVar object is allocated automatically.
> pInt=&iVar;
Correct, pInt points to iVar object.

> [SECOND]
> int *pInt=NULL;
> int iVar=10;
> pInt=(int*)malloc(1*sizeof(int));
Correct, you allocate new memory and assign pInt to it.
> pInt=&iVar;
Correct, but you reassign pInt back to iVar object again.

> I really need to allocate memory before assign an address to a pointer
> variable?.

No, when you define a variable, the memory is allocated automatically.
The variable is the object, and a pointer may point to it.

Simplifying a little, one can say that you can have as many objects
as many variables you have in your program. If you need more objects,
then you need to allocate.

> Thus because i know that declaration not allocate memory for pointer
> variable.
> Is correct ?.

Correct. Pointer definition automatically allocates memory only for
the pointer variable itself (yes, the pointer is also kind of object),
but *not* for what the pointer is supposed to point at (the pointer is
said to be "dangling", until you assign to something valid).

-- 
Stan Tobias
sed 's/[A-Z]//g' to email


Relevant Pages

  • Re: Is There Any Reason to Even Use VC++ Anymore?
    ... If, for another reason, the calling function needs to allocate memory, ... It does this by taking a pointer to a ball object ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Pointer to the out of scope local variables
    ... of a pointer, and jumped to the conclusion that you allocated the memory ... In this particular case the funtion buildPoint would allocate ... If the caller ...
    (microsoft.public.vc.language)
  • Re: Memory management and allocation
    ... > As I'm writing a piece of code that basically acts as a server and ... > memory management is a topic that is quite crucial. ... Or can I just allocate the variable ... Nor is it usually necessary to set the pointer to ...
    (comp.lang.c)
  • Re: Virtual Machine implementation problem, Please help me to spot the bug
    ... I kept on getting error messages. ... You don't allocate enough memory here. ... Again conversions between pointer and integer types. ...
    (comp.lang.c)
  • Re: This is getting really weird.
    ... I thought 4 bytes for reference count and 4 for string length. ... > There should be no memory allocation for that line. ... > manager may allocate more space than requested for its own efficiency. ... > that New returned with a pointer to the string constant. ...
    (alt.comp.lang.borland-delphi)