Reputation: 33
Below code doesn't give any allocation error , however the counting ends at about 16970 with memory allocation error and system halted ,I use Turbo C++ 3.0 IDE ,Windows XP sp3 , all partitions : NTFS ,PC : Dell 1545 with 2 GB ram installed .
#include <stdio.h>
#include <stdlib.h>
long counter=0;
int main(int argc, char *argv[])
{
char* array=(char*) malloc (1024*1024*10);
if (array==NULL)
{
/* allocation error */
return 1;
}
for (counter=0 ; counter<10000000;counter++)
array[counter] = 1; // trying to fill the array with one's
free (array);
return 0;
}
Upvotes: 0
Views: 861
Reputation: 2438
Turbo C++ worked in a DOS environment, in real mode unless you specifically enable protected mode. In real mode, memory space is broken into 64kbyte segments, and size_t (the parameter for malloc) could easily be 16 bits. 1024*1024*10 mod 65536 = 0, so the call to malloc above works out to malloc(0)
.
The return value of malloc(0) is implementation-defined, and may be nonzero. (what does malloc(0) return?) Using the returned pointer would be a bad idea, and Windows XP might be intervening with the memory allocation error.
Upvotes: 4