[英]dynamic memory allocation using new with binary search in C++
I am trying to find the maximum memory allocated using new[]. 我试图找到使用new []分配的最大内存。 I have used binary search to make allocation a bit faster, in order to find the final memory that can be allocated
我使用了二进制搜索来使分配更快一些,以便找到可以分配的最终内存
bool allocated = false;
int* ptr= nullptr;
int low = 0,high = std::numeric_limits<int>;
while(true)
{
try
{
mid = (low + high) / 2;
ptr = new int[mid];
delete[] ptr;
allocated = true;
}
catch(Exception e)
{....}
if (allocated == true)
{
low = mid;
}else
{
high = low;
cout << "maximum memory allocated at: " << ptr << endl;
}
}
I have modified my code, I am using a new logic to solve this. 我已经修改了代码,正在使用一种新的逻辑来解决这个问题。 My problem right now is it is going to a never ending loop.
我现在的问题是,这将是一个永无止境的循环。 Is there any better way to do this?
有什么更好的方法吗?
This code is useless for a couple of reasons. 出于以下几个原因,此代码无用。
new
happily returns a new memory address, but it doesn't make the memory available just yet. new
高兴地返回一个新的内存地址,但是它尚不能使内存可用。 It is actually allocated later when and if a corresponding address is accessed. int
is 32 bits, alloc
will eventually overflow and become negative before the memory is exhausted. int
为32位,则alloc
最终将溢出,并在内存耗尽之前变为负数。 Then you may get a bad_alloc. size_t
for all things that are sizes. size_t
用于所有大小的东西。 Assuming you are doing ++alloc and not ++allocation, it shouldn't matter what address it uses. 假设您正在执行++ alloc而不是++ allocation,则使用的地址无关紧要。 if you want it to use a different address every time then don't delete the pointer.
如果您希望它每次使用不同的地址,则不要删除指针。
This is a particularly bad test. 这是一个特别糟糕的测试。
For the first part you have undefined behaviour . 对于第一部分,您具有未定义的行为 。 That's because you should only ever
delete[]
the pointer returned to you by new[]
. 这是因为您只应该
delete[]
new[]
返回给您的指针。 You need to delete[] pvalue
, not value
. 您需要
delete[] pvalue
,而不是value
。
The second thing is that your approach will be defragmenting your memory as you're continuously allocating and deallocating contiguous memory blocks. 第二件事是当您连续分配和取消分配连续的内存块时,您的方法将对内存进行碎片整理。 I imagine that your program will understate the maximum block size due to this fragmentation effect.
我想由于这种碎片效应,您的程序将低估最大块大小。 One solution to this would be to launch instances of your program as a new process from the command line, setting the allocation block size as a parameter.
一种解决方案是从命令行将程序实例作为新进程启动,并将分配块大小设置为参数。 Use a divide and conquer bisection approach to attain the maximum size (with some reliability) in log(n) trials.
在log(n)试验中,使用分而治之的对分方法来获得最大大小(并具有一定的可靠性)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.