0

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;
    }
Howard
  • 33
  • 8

1 Answers1

4

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.

Neil
  • 2,378
  • 1
  • 20
  • 28
  • ( 1024*1024*10 mod 65536 = 0, so the call to malloc above works out to malloc(0) ) ,, this should return a 'NULL' pointer , but that wouldn't happen ! – Howard Aug 12 '16 at 21:46
  • so , the problem here is in the TC++ compiler ? then , should I replace it ? – Howard Aug 12 '16 at 21:56
  • @howard Yes, you should replace this compiler with something newer. (And you should probably replace Windows XP with something newer, while you're at it. ;-) – zwol Aug 13 '16 at 00:02
  • what about 'farmalloc' ? at all I should finish this project with ms dos compilers – Howard Aug 13 '16 at 05:59
  • @Howard: `malloc(0)` is allowed to return a valid pointer to zero bytes of memory. – Nisse Engström Aug 13 '16 at 07:38