Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scope of memory allocated by Malloc/Realloc

Status
Not open for further replies.

nagendra4u

Programmer
Mar 17, 2005
1
IN
What is the scope of the memory allocated by either of Malloc or Realloc?

I mean if in a function i allocate some memory using Malloc/Realloc, can I use the same memory location using a pointer from some other fucntion?

In specific, there is CHAR pointer defined in function A. I call function B and pass this CHAR pointer to it. In function B i allocate some memory to this pointer. Will this allocated memory be accessible from function A?

Cheers
Nagu
 
1. May be, malloc/realloc, not Malloc/Realloc (case-sensitive names in C;)?
2. Time of life aspect called duration, not a scope.

Allocated by malloc() family objects lives until you explicitly destroy its by free().

You can access allocated storage chunk only via pointer value returned by correspondent malloc. For example:
Code:
void f()
{
   char* p = malloc(100);
   ....
}
You can't access this memory after f returns (automatic variable p will be discarded and its value losted).

In function B i allocate some memory to this pointer.
It's nonsense. You can't allocate memory to this pointer. You can change value of this pointer (and lost its previous value).
 
If coding in C style in a project that is compiled into a C++ project or with a C++ compiler... Don't mix alloc/realloc/free with new/delete ... behavior is undefined, may cause memory leaks and is simply not a good idea.

In specific, there is CHAR pointer defined in function A. I call function B and pass this CHAR pointer to it. In function B i allocate some memory to this pointer. Will this allocated memory be accessible from function A?
Code:
void B0(char *p)
{
 p = alloc(100)
} 
// Memory leak, no way to get at it because you 
// passed by value.  This COPY of p is destroyed,
// there is no handle to the memory allocated, so
// it cannot be freed.  [red]DON'T DO THIS[/red]

void B1(char*[green]&[/green] p)
{
 p = alloc(100)
}
// Memory is avalible through p, as p is passed by
// refference, the actual value in the calling function (A)
// does take on the address of the newly aollocated memory

[green]char*[/green] B3(char *p)
{
 p = alloc(100)
 [green]return p[/green]
}
// address of the memory is now being returned.  
// Why you'd pass the pointer in, doing this way,
// is beyond me.

[plug=shameless]
[/plug]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top