Article View: gnu.gcc.help
Article #41897Re: float *func() messes up memory??
From: Piet van Oostrum
Date: Mon, 12 Feb 1996 00:00
Date: Mon, 12 Feb 1996 00:00
54 lines
2627 bytes
2627 bytes
>>>>> schilling@hpbio1.Biologie.HU-Berlin.de (Andre Schilling) (AS) writes:
AS> Writing a function that returns a pointer to an array of real numbers I
AS> always get the proper pointer but - for some unknown reason - the
AS> values in the array pointed to are incorrect. Examining the function
AS> itself neither the pointervalue nor the actual numbers in the array are
AS> wrong. But trying to call them after they have been returned from the
AS> function always results in some kind of random numbers in the array.
AS> Important: the pointer returned by the function and the pointer
AS> received by the calling function are the same. Only the values in the
AS> array have changed which has given me some thought for the past days.
AS> Does anyone know the reason for that?? Here s the sample program:
AS> int *DomainSize(void)
AS> {
AS> int *PDomainS ;
AS> int i,DomainS[5] ;
AS> PDomainS = DomainS ;
AS> for (i=0;i<5;i++) {
AS> DomainS[i] = i+11 ;
AS> }
AS> return(PDomainS) ;
AS> }
AS> void main(void)
AS> {
AS> int *PG ;
AS> int i ;
AS> PG = DomainSize() ;
AS> for (i=0;i<5;i++)
AS> printf("%i \n",*(PG+i)) ;
AS> }
AS> the pointer PDomainS in DomainSize() points to the first element in
AS> DomainS[]. This value is passed to PG (in main) correctly. But printing
AS> the values of *(PG+i) results in arbitrary numbers. Once you ve got the
AS> right pointer you should find the proper numbers in the memory, shouldn
AS> t you??
The pointer you return points to the stack frame of the function
DomainSize. After you return, the stack frame is popped from the stack and
therefore the pointer gets invalid, or if you want to say it differently,
the memory locations that it points to get reused by subsequent
instructions, in this case the calls to printf. If you want to return a
pointer to some data area from your function you must either declare the
data area (DomainS) static, or allocate it with malloc, and let the
receiver free it in due time.
--
Piet van Oostrum <piet@cs.ruu.nl>
http://www.cs.ruu.nl/~piet
Technical Details
Message-ID:
<wzhgwwk846.fsf@stego.cs.ruu.nl>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailReferences:
<4fnblm$b30@news.cs.tu-berlin.de>Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 11318c,6915249633026d70 X-Google-Attributes: gid11318c,public From: piet@stego.cs.ruu.nl (Piet van Oostrum) Subject: Re: float *func() messes up memory?? Date: 1996/02/12 Message-ID: <wzhgwwk846.fsf@stego.cs.ruu.nl> X-Deja-AN: 139017465 sender: piet@stego.cs.ruu.nl references: <4fnblm$b30@news.cs.tu-berlin.de> to: schilling@hpbio1.Biologie.HU-Berlin.de (Andre Schilling) organization: Universiteit Utrecht, Dept. of Computer Science newsgroups: gnu.gcc.help