pastebin - collaborative debugging tool
rovema.kpaste.net RSS


c++pmr1.cpp PMR buffer too small test 1
Posted by Anonymous on Mon 18th Nov 2024 08:48
raw | new post
modification of post by Anonymous (view diff)

  1.  
  2. /*
  3.  * c++pmr1.cpp - Simple C++17 PMR example+out-of-memory condition
  4.  *
  5.  * Compile and run with
  6.  * ---- snip ----
  7.  * rm -f a.exe* ; clang++ -target x86_64-w64-mingw32 -std=c++17 -Bstatic c++pmr1.cpp
  8.  * ---- snip ----
  9.  * OR (Cygwin 3.6 with gcc 15.0):
  10.  * ---- snip ----
  11.  * rm -f a.exe* ; g++ -std=c++20 -Wall -Wextra -D_GLIBCXX_USE_CXX11_ABI c++pmr1.cpp
  12.  * ---- snip ----
  13.  *
  14.  * Output:
  15.  * ---- snip ----
  16.  * $ PATH+=':/usr/x86_64-w64-mingw32/sys-root/mingw/bin/' ./a.exe
  17.  * # Cycle: 0: str='x'
  18.  * # Cycle: 1: str='xx'
  19.  * # Cycle: 2: str='xxxx'
  20.  * # Cycle: 3: str='xxxxxxxx'
  21.  * # Cycle: 4: str='xxxxxxxxxxxxxxxx'
  22.  * DIE!!std::bad_alloc
  23.  * ---- snip ----
  24.  *
  25.  * Written by Roland Mainz <roland.mainz@nrubsig.org>
  26.  */
  27.  
  28. #include <array>
  29. #include <cstddef>
  30. #include <iostream>
  31. #include <memory_resource>
  32.  
  33.  
  34. int main(int ac, char *av[])
  35. {
  36.         char buffer[4096];
  37.  
  38.         /*
  39.          * Note that without |std::pmr::null_memory_resource()| |monotonic_buffer_resource()| will
  40.          * use the default memory resource to obtain memory if it runs out of memory
  41.          */
  42.         std::pmr::monotonic_buffer_resource pool{buffer, sizeof(buffer), std::pmr::null_memory_resource() };
  43.         std::pmr::polymorphic_allocator<char> pa{&pool};
  44.         std::pmr::string s{"12", pa};
  45.         std::pmr::string s2{pa};
  46.         std::pmr::string s3{pa};
  47.         std::pmr::string s4{pa};
  48.  
  49.         try {
  50.                 for (int i=0 ; i < 8 ; i++) {
  51.                         std::cout << "# Cycle: " << i << ": str='" << s << "'" << std::endl;
  52.                         s2 = s;
  53.                         s3 = s;
  54.                         s4 = s2 + s3;
  55.                         s = s4;
  56.                 }
  57.  
  58.                 std::cout << s << std::endl;
  59.         } catch(const std::exception &e) {
  60.                 std::cerr << "DIE!!" << e.what() << std::endl;
  61.         }
  62.  
  63.         return EXIT_SUCCESS;
  64. }

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}




All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at