Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!bria!mike Newsgroups: comp.lang.c Subject: Re: Why declare returned pointers static? Message-ID: <484@bria> Date: 25 Feb 91 14:49:29 GMT References: <1991Feb25.074222.12846@msuinfo.cl.msu.edu> Reply-To: uunet!bria!mike Organization: MGI Group International, Los Angeles, CA Lines: 32 Followup-To: Keywords: 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. -- Michael Stefanik, MGI Inc., Los Angeles| Opinions stated are not even my own. Title of the week: Systems Engineer | UUCP: ...!uunet!bria!mike ------------------------------------------------------------------------------- Remember folks: If you can't flame MS-DOS, then what _can_ you flame?