Menu

#1372 In C++ mode %new_copy and similar macros in swigmacros.swg don't handle std::bad_alloc

open
nobody
None
5
2023-06-24
2014-06-04
someone
No

%new_copy and similar macros in swigmacros.swg use plain operator new in C++ mode which throws std::bad_alloc when it fails to allocate memory, since this macro is used in typemaps this exception won't be caught and will crash the process.

In C mode this macros use malloc and friend which will simply return NULL, which will cause SWIG to return None,nil or some such in most languages, while not the best behaviour (It should raise a MemoryError or something similar) at least it doesn't crash.

Discussion

  • Olly Betts

    Olly Betts - 2022-03-15

    This still seems to be the case for current SWIG versions.

    Perhaps SWIG should specify non-throwing new - e.g.:

    # define %new_copy(val,Type...)             (new(std::nothrow) Type(%static_cast(val, const Type&)))
    

    And add #include <new> too.

    Then an allocation failure will return NULL like malloc() does.

     
  • Olly Betts

    Olly Betts - 2023-06-24

    I've opened a PR with that change: https://github.com/swig/swig/pull/2644

     

Log in to post a comment.