Hi,

I am getting an error when running a code on linux machine:

"terminate called after throwing an instance of 'std::bad_alloc'
what(): St9bad_alloc
Aborted"

In my code i have a 2 dimensional vector defined.

Can someone tell me the possible cause of error.

Thanks

Dani AI

Generated

A short, practical diagnosis and next steps.

std::bad_alloc means the allocator failed to satisfy a memory request (operator new threw) rather than directly signaling an out‑of‑bounds access; it usually happens when a requested allocation is too large or the system cannot provide more memory. See the C++ reference for details on std::bad_alloc and operator new: . was right to flag invalid memory access as something to check — out‑of‑range writes or corrupted heap state can make later allocations fail unpredictably.

Quick checklist to narrow the cause:

  • Log the sizes you pass to resize/reserve before allocating. Large or negative values (signed overflow or implicit conversion to size_t) can produce enormous allocation requests.
  • On nested vector<vector<T>>, each inner vector does a separate allocation; a few billion elements will exhaust memory quickly. See std::vector.
  • Use vector::at to get bounds‑checking (std::out_of_range) while debugging instead of operator[] (vector::at).
  • Check process limits and address‑space (32‑bit processes hit lower limits), and monitor free memory with free -m or /proc/meminfo.

Practical debugging steps:

  • Print rows/cols and the product before allocation. Check for rows > SIZE_MAX / cols to avoid overflow.
  • Build and run under sanitizers: compile with -fsanitize=address,undefined -g -O1 to catch out‑of‑bounds/UB; or run under Valgrind for heap errors.
  • Wrap suspected allocations in try/catch to log context when std::bad_alloc occurs.

If the matrix is large, prefer a single contiguous buffer for performance and predictable allocation:

std::vector<T> data(rows * cols);
auto at = [&](size_t r, size_t c) -> T& { return data[r*cols + c]; };

This reduces many small allocations and makes it easier to reason about total memory. noted the original tip helped — combine these checks and sanitizer runs to find whether the failure is a true out‑of‑memory or the result of prior heap corruption.

Recommended Answers

All 2 Replies

Check if you are accessing memory that you have not allocated. Are you using an invalid pointer? Are you using pointers?

Are you referencing an iterator on the end of a vector? (ex: it.end())

Without source code, I cannot give you more advice. I hope that this tips will help.

Thanks.. your advise helped

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.