I'm trying to load a traced PyTorch model in C++ using LibTorch but encountering a std::bad_alloc error. I've set up a minimal example to demonstrate the issue.
The Problem: When running my C++ application that loads a PyTorch model, it crashes with:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
cpp code :
#include <iostream>
#include <memory>
#include <torch/script.h>
int main()
{
// Load the traced model
torch::jit::script::Module module;
// Load the saved model - update path to your .pt file
module = torch::jit::load("net.pt");
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
project(torch_example)
include(FetchContent)
set(LIBTORCH_CPU_URL "https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-2.5.1%2Bcpu.zip")
FetchContent_Declare(
Torch
URL ${LIBTORCH_CPU_URL }
DOWNLOAD_EXTRACT_TIMESTAMP TRUE
)
FetchContent_MakeAvailable(Torch)
add_executable(torch_example main.cpp)
target_link_libraries(torch_example PRIVATE "${TORCH_LIBRARIES}")
target_include_directories(torch_example PRIVATE "${torch_SOURCE_DIR}/include")
set_target_properties(torch_example PROPERTIES CXX_STANDARD 23)

std::bad_alloccan be thrown if the argument being given tonew[]is negative. See this.