Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dividing by zero causes memory leak in Borland C++

I'm simply running the following code in Borland C++ Builder Version 6;

for (int i = 0; i < 40000; i++)
{      
   try {
     __int64 n = 0;
     __int64 r = 1 / n;
   }
   catch (Exception& e) {}
}

and while running this loop, I see in task manager (Memory column) that it's leaking memory. Any idea why?

I was having memory leak while working on a calculating module in my project when I try to divide by zero and after hitting my head for many hours where is the memory leak, I realized that it's leaking memory in the above simple loop as well. No problem was found in the project.

like image 623
nommyravian Avatar asked Sep 18 '13 14:09

nommyravian


1 Answers

From the standard 5/4 we learn that:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

So since division by zero is not mathematically defined, the behavior is undefined. Undefined behavior includes memory leaks, so it's not really worthwhile to speculate further on why it's leaking memory (although a tool like valgrind might be able to help you identify a source).

like image 83
Mark B Avatar answered Sep 28 '22 07:09

Mark B