Path: utzoo!attcan!uunet!munnari.oz.au!comp.vuw.ac.nz!cavebbs!frank From: frank@cavebbs.gen.nz (Frank van der Hulst) Newsgroups: comp.lang.c Subject: Re: Why declare returned pointers static? Message-ID: <1991Mar01.081914.13539@cavebbs.gen.nz> Date: 1 Mar 91 08:19:14 GMT References: <1991Feb25.074222.12846@msuinfo.cl.msu.edu> <484@bria> Organization: The Cave MegaBBS, Public Access Usenet, Wellington, NZ Lines: 38 In article <484@bria> uunet!bria!mike writes: >In an article, draper@galaxy.cps.msu.edu (Patrick J Draper) writes: >|DATA_STRUCTURE *foo () >|{ >| static DATA_STRUCTURE *bar; >| >| bar = (DATA_STRUCTRE *) malloc (sizeof (DATA_STRUCTRE)); >| return (bar); >|} >| >|and called like this: >|DATA_STRUCTRE *bar; >| >| bar = foo (); >| >|My question is: Why does this work? Is the malloc'd space static and not >|the pointer? From my tests with Turbo C++, with a static pointer, the >|malloc'd space never gets overwritten accidentally. With a normal >|pointer, the malloc'd space can be corrupted by things like another >|malloc, etc. > >Memory that has been allocated ala malloc() is global within the context >of the process allocating it. The pointer is not. Remember, when you >declare a pointer, you *are* declaring storage (for the address). If the >pointer is an automatic variable, the memory that contains the address >is released unless it is declared static. Your chunk of memory that you >grabbed with malloc() is still there; the pointer to it is not. > But the contents of the pointer (i.e. the address of the malloc'ed memory) is being returned (presumably via CPU registers) to be stored in ably) yet another DATA_STRUCTURE * variable. So it doesn't matter if the bar variable inside foo() is lost. Unless TC++ is attempting some garbage collection at the end of foo(), and doesn't realise that the memory is still being used, and pointed to in the CPU registers. -- Take a walk on the wild side, and I don't mean the Milford Track.