Re: memory leak (well, kind of...) ?
Posted in 1993
OK, I plead guilty to not testing my C code. Two people have picked me up on the bug in the loop condition in the C code: >Subject: Re: memory leak (well, kind of...) ? >Reply-To: spitz@ana.med.uni-muenchen.de >In article <1spl0mINN67p@emory.mathcs.emory.edu> you wrote: >: Here's a simple program that eventually crashes on most machines: >: #include <string.h> >: #include <stdlib.h> >: int main() >: { >: void *v = 0; >: long l = 0; >: while (l > 0) >: { >: v = realloc(v, l += 1024); >: strcpy(v, "Abyssinia"); >: } >: return(0); >: } >Did you make a typing mistake in the above program? I tried it on several >machines and it didn't do anything. >I'm always interested in improving my rather poor C programming skills, >so I eagerly jumped on this program, hoping to learn something from it. >So far, I didn't ;-) >As I see it, the while-loop is never entered, since the condition l>0 >is never met. Correct. >From: uunet!cbnewsg.cb.att.com!ashaw (andrew.shaw) >Subject: Re: memory leak (well, kind of...) ? >Date: Wed, 12 May 1993 16:38:36 GMT >X-Informix-List-Id: <news.3305> >Actually it should never crash on any machine. Indeed, the whole >program (as written) should optimize to "main() { return (0); }". Also correct. >> Just because it can be written doesn't make it sensible. > >No argument with that. Gosh, someone agrees with me. The loop condition should be ">=", not ">". The point behind that test is to worry about when the long arithmetic overflows and the answer goes negative, but that would require a machine which supports 2 GB of virtual memory successfully. Some machines may handle it because I don't actually write in 99.99999% of the memory, but most will decline to provide that much memory and will return 0, which I go trampling on and which should (but may not) cause the program to crash with a core dump. A better version of the strcpy line would use a loop: for (i = 0; i < l; i += 1024) strcpy(&v[i], "Abyssinia"); Obviously, you'd need to declare i as a long too. Sorry, I hadn't actually run that code -- as you noticed. Yours Jonathan Leffler (johnl@obelix.informix.com) #include <disclaimer.h>