Message-Id: <199801080906.LAA06335@ankara.duzen.com.tr> Comments: Authenticated sender is From: "S. M. Halloran" Organization: User RFC 822- and 1123-Compliant To: David Eberhard Date: Thu, 8 Jan 1998 11:07:28 +0200 MIME-Version: 1.0 Content-type: text/plain; charset=US-ASCII Content-transfer-encoding: 7BIT Subject: Re: problem with memory allocation (I think) CC: djgpp AT delorie DOT com In-reply-to: <34B47DFA.E0D6D796@xmission.com> Precedence: bulk On 8 Jan 98, David Eberhard was found to have commented thusly: > I am getting a runtime error when running my program. Here is the > part that is not running correctly: > > long i; > unsigned int *buffer; > buffer = malloc(640 * 480 * 2); > for(i = 0; i < 640*480; i++) > { > buffer[i] = i; > } > > > and here's the error message I get: > > Exiting due to signal SIGSEGV > General Protection Fault at eip=0000194a > eax=001c0000 ebx=00021fff ecx=00006ccc edx=0000006c esi=00021ffe > edi=00000005 ebp=0004efe0 esp=0004eebc > program=c:/cplus/djgpp/graphics.exe Well, yes...you are certainly challenging the system's memory protection system...it seems. Since it is W95, I am a little surprised that you were not immediately sent to Land of Warm Reboot :) > > If I change the for loop so that it only loops 640*480/2 times, then > it works fine. Can anyone tell me what's going on? > Notice that buffer is a pointer to an array of 'int' data type. In your malloc, you are assuming that an 'int' type has a sizeof(int) = 2. Shame on you! :) On the DJGPP compiler system, it is assumed that the natural integer type (the essential quality of 'int') is 32 bits (4 bytes), not 16 (2 bytes). So there you are. Actually, you will always be on safer ground by writing the ultimately portable set of expressions as follows: /* -------- */ { unsigned long i, max; /* made 'i' unsigned -- could be good idea */ unsigned int *buffer; max = 640UL * 480UL * sizeof(unsigned int); buffer = malloc(max); for(i = 0UL; i < max; i++) { buffer[i] = i; } Note you have another problem with the code. Expression 'buffer[i] = i' assigns an unsigned long to an unsigned int. A warning should have alerted you to this fact (I hope you have your all your warnings set!). Since sizeof(unsigned long) = sizeof(unsigned int) on DJGPP, you are fortunate, but don't count on that behavior in other systems. You should at any rate either re-type 'i' or 'buffer', or as a last choice, use a cast. Just so long as you are aware of the implications. Mitch Halloran Research (Bio)chemist Duzen Laboratories Group Ankara TURKEY mitch AT duzen DOT com DOT tr other job title: Sequoia's (dob 12-20-95) daddy