Can anyone tell me why setprecision is causing this error at runtime:

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

The program ran fine; after I added << setprecision(2) << to a series of output, I received the error when trying to run the program. I have included iomanip and the program will run fine if I remove the setprecision manipulator. Thanks for any help.

Here is the snippet of code where I'm trying to use setprecision, avgWait is a float variable:

//Calculate average waiting time,
  //.005 added to round to nearest hundreth of a time unit
  avgWait = ((float)totalWait/totCust) + .005;
  
  cout<< endl << "The simulation ran for " << sTime << " time units" << endl
      << "Number of servers: " << numServers << endl
      << "Average transaction time: " << tTime << endl
      << "Average time between customer arrivals: " << tbArrival << endl
      << "Total waiting time: " << totalWait << endl
      << "Number of customers that completed a transaction: " << servedCust
      << endl
      << "Number of customers left at servers: "
      << servers.getNumberOfBusyServers() << endl
      << "Number of customers left in the queue: " << customers.size() << endl
      << "Average waiting time: " << fixed << setprecision(2) << avgWait << endl
      << "***************END SIMULATION***************" << endl;

Dani AI

Generated

Given 's follow-up that the exception went away after fixing other bugs, the most likely explanation is not a bug in the manipulator itself but latent undefined behaviour (heap corruption, out‑of‑bounds access, use-after-free, etc.) being exposed by a change in program execution. The setprecision manipulator and the iostream formatting path can touch locale/formatting code and trigger allocations that previously never occurred; if allocator metadata is already corrupt, the first allocation can throw std::bad_alloc. See and the setprecision reference for background.

Practical steps to find the real fault:

  • Run with AddressSanitizer or Valgrind to catch heap corruption, buffer overruns, and use-after-free. Example tools: AddressSanitizer and Valgrind.
  • Build libstdc++ in debug mode to detect invalid container usage: compile with -D_GLIBCXX_DEBUG.
  • Turn on iostream exceptions and catch them to see where stream code fails.

Example commands and small patterns to try:

g++ -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer main.cpp -o main
valgrind --leak-check=full --track-origins=yes ./main
g++ -g -O0 -D_GLIBCXX_DEBUG main.cpp -o main
cout.exceptions(std::ios::badbit | std::ios::failbit);
try {
    // your output statements here
} catch (const std::exception& e) {
    cerr << "i/o exception: " << e.what() << '\n';
}

Quick checklist before deep debugging: ensure denominators are nonzero, validate indices and iterators, check lifetime of objects used in output, and look for mismatched new/delete. Because fixing other bugs removed the failure, the root cause was almost certainly elsewhere; use sanitizers and a minimal reproducer to find it so setprecision can stay in place safely.

Recommended Answers

All 2 Replies

.

After fixing other seemingly unrelated problems with the program, the error stopped occurring. Still, it would be nice to know how just adding the setprecision manipulator caused this error.

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.