Hi,

I am getting the following error:

test.o(5209) malloc: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

I am using finite recursive function in my program.

Please help with my query.

Thanks

Dani AI

Generated

The allocator failure reported by usually means the process exhausted available memory or address space while the program was recursing. was right to point at the recursion logic, called attention to allocation issues, and highlighted per-call allocation risk — all useful directions. Two distinct problems produce this symptom: very deep recursion that consumes stack frames, and many live heap allocations made per recursion level so total resident memory grows until mmap fails.

Immediate, practical checks:

  • Add a simple depth counter or guard so the routine returns if depth exceeds a sane limit; log the depth when the crash happens to see how deep you actually go.
  • Build and run under sanitizers (Clang/GCC: -fsanitize=address,leak), or use platform tools (Instruments on macOS) to watch heap growth and find the allocation site.
  • Verify process limits with ulimit -a (or platform equivalent) to ensure you aren’t hitting an imposed address-space cap.
  • Set an allocator breakpoint in the debugger to get a backtrace at the failure point (use the debugger’s breakpoint command for the malloc failure hook).

Small, safe changes to try:

std::vector<char> buffer(4096); // created once
recurse(startDepth, buffer);

Pass a reusable buffer or context down the recursion instead of allocating new buffers at each call. Alternatively, refactor the algorithm to an explicit stack/loop so memory isn’t proportional to recursion depth.

If per-call buffers must exist, ensure they are freed before recursing (or use RAII/container ownership), and consider increasing thread stack size only as a last resort. Use sanitizers and the debugger backtrace to pinpoint whether this is stack exhaustion, a leak, or simply too many simultaneous allocations.

Recommended Answers

All 3 Replies

Nobody can help you if you don't post the code. Maybe your recursive function didn't know when to stop and cause stack overflow or something else just as bad. Check to see if there is something in the function that will make the recursion stop. Also make it stop after only a few recursions and see if the same error occurs.

Did you declare a pointer without allocating memory?

type_of_var *p;
p = new type_of_var; // allocate memory

We're really completely in the dark without any code.

or may be your code look like this

void foo()
{
  char* tmp = new char[1024];
  foo();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.