0

I am writing unit tests for a library I am developing. The library implementation cannot be mocked. The unit test is about returning a special value when the program runs out of memory.

I came up with this naive solution:

// Fillup memory
int *p = NULL
do {
    p = malloc(sizeof(int));
    // store p somewhere to release it later
} while(p);
// Got out of memory :)

Is there anyway to fill up the memory faster than this solution without increasing the memory block size allocated with malloc ?

PS: Using a third party memory allocator is forbidden :)

David Andreoletti
  • 4,485
  • 4
  • 29
  • 51

2 Answers2

1

Obviously - but depending on the C++ implementation - you could do that in multiple threads. Besides that - no.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • The question is about C not C++ :) – David Andreoletti Feb 23 '14 at 07:05
  • I am not sure how creating more than 1 thread would help with this ? I am pretty confident `malloc` will queue up the requests: http://stackoverflow.com/questions/4859263/can-multithreading-speed-up-memory-allocation – David Andreoletti Feb 23 '14 at 07:11
  • I am not sure - this is why I said it is implementation dependent. There are compilers having very lock free implemeentations assigning different htreads memory out of different pools. That said, it is the ONLY way that would work because you already have a super tight loop. Nothing else left. – TomTom Feb 23 '14 at 07:13
  • Sorry, I missed the "implementation dependent" bit. – David Andreoletti Feb 23 '14 at 07:15
1

Try allocating bigger memory chunks rather than sizeof(int). e.g. 1KB and when allocation fails keep on reducing the size argument in the loop. Do this till allocation fails for sufficiently small size - May be 1 B.

Yogesh
  • 565
  • 3
  • 21