bug-glibc
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Problem with malloc on very large blocks of memory


From: Dan Klebanov
Subject: Problem with malloc on very large blocks of memory
Date: Fri, 21 Mar 2003 16:47:00 -0500
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.1) Gecko/20021003


I've found a problem with malloc on systems with swap disabled. In particular, when attempting to allocate very large blocks of memory, malloc will often return a legitimate pointer to a chunk of memory which is corrupted at the end of the block.

I'm using a RedHat 7.2 system (glibc-2.2.4-13) with kernel 2.4.20-pre6.

I wrote a small program which demonstrates this bug on my system. It attempts to find the largest possible allocatable block, and then it writes to that block. Towards the end of the write (usually >98% close to the end of the block), it gets a SIGKILL from the system.

If anyone knows anything about this problem, I'd be grateful to hear back from you. Please cc your message to dan_klebanov at yahoo dot com. thanks.

Dan


#include <stdio.h>

int findLargestChunk (int smallest, int biggest)
{
 int mid;
 char* m;

 if ( (biggest - smallest) < 256) return smallest;

 mid = (biggest + smallest)/2;
 m = (char*) malloc(mid);
 if (!m) {
   return findLargestChunk (smallest, mid);
 }
 else {
   free(m);
   return findLargestChunk (mid, biggest);
 }
}

int checkForSwap()
{
 int linecount=0;
 char line[256];
 FILE* f = fopen("/proc/swaps", "r");
 if (!f) {
   fprintf(stderr, "Failed to open /proc/swaps\n");
   return -1;
 }
 while (fgets(line, 255, f) != NULL) {
   linecount++;
 }
 if (linecount>1) return 1;
 else return 0;

}


int main(int argc, char** argv)
{
 int haveswap=0;
 int i, bytes=0, mb=0;
 char* p = NULL;

 bytes = findLargestChunk(0, 0x7fffffff);
 mb = bytes / (1024*1024);
 printf("\nLargest allocatable chunk of memory = %d MB  (%d bytes)\n",
    mb, bytes);

 while (!p) {
   p = (char*) malloc (bytes);
   if (!p) bytes -= 256;
 }
 mb = bytes / (1024*1024);

 printf("allocated  %d MB  (%d bytes)\n", mb, bytes);
 haveswap = checkForSwap();
 if (haveswap!=0) {
printf("\n\nTurn off swap before running this program, or you'll be sorry!!\n");
 }

printf("\nAt your own peril, press Enter to write to this memory block...\n");
 getchar();

 for (i=0; i<bytes; i++) {
   if (!(i%100000)) {
     printf("writing to memory  i=%d / %d    %.2f%% \n", i,
        bytes, 100. * (float)i/bytes);
   }
   p[i] = 0;
 }
 printf("Success !  Your malloc seems to work fine.\n");
}







reply via email to

[Prev in Thread] Current Thread [Next in Thread]