【发布时间】:2018-06-06 18:48:39
【问题描述】:
我试图测试堆溢出: 因此,我在向量中添加了很多虚拟元素。 我的期望:某种异常(错误的分配或类似的东西)。
(因为向量是一个连续的内存区域,一旦向量增长,可能会发生重新分配。我想知道如何检测添加元素是否有效。 根据http://www.cplusplus.com/reference/vector/vector/push_back/ push_back 没有返回值)。
此外,我还定义了一个自定义终止处理程序。自定义终止处理程序设置在引发堆溢出之前。
我正在将我的终止处理程序设置为自定义处理程序
void CFatal_Error::Set_Termination_Handler()
{
set_terminate(Termination_Handler);
}
void CFatal_Error::Termination_Handler()
{
// crash and stop here
configASSERT(0);
}
堆溢出是由
引起的vector<uint32_t> test;
try
{
for (uint32_t i = 0; i < UINT32_MAX; i++)
{
test.push_back(i);
}
}
catch (const exception &ex)
{
configASSERT(0);
}
首先,我预计我会遇到异常,但我会直接遇到一个硬故障。有人可以解释这种行为吗?
使用的编译器标志:
Building file: ../Test_SD.cpp
Invoking: MCU G++ Compiler
\Debug
arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 '-D__weak=__attribute__((weak))' '-D__packed=__attribute__((__packed__))' -DUSE_HAL_DRIVER -DSTM32F429xx -I"Inc" -I"Inc/User" -I"xxx/Inc/User/debug" -I"xxx/Inc/User/Testcases" -I"xxx/Inc/User/display" -I"xxx/Inc/User/SD" -I"xxx/Inc/User/SD/XML" -I"xxx/Drivers/STM32F4xx_HAL_Driver/Inc" -I"xxx/Drivers/STM32F4xx_HAL_Driver/Inc/Legacy" -I"xxx/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F" -I"xxx/Middlewares/ST/STM32_USB_Device_Library/Core/Inc" -I"xxx/Middlewares/ST/STemWin/Config" -I"xxx/Middlewares/ST/STemWin/inc" -I"xxx/Middlewares/ST/STM32_USB_Device_Library/Class/CustomHID/Inc" -I"xxx/Drivers/CMSIS/Device/ST/STM32F4xx/Include" -I"xxx/Middlewares/Third_Party/FatFs/src" -I"xxx/Middlewares/Third_Party/FreeRTOS/Source/include" -I"xxx/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS" -I"xxx/Drivers/CMSIS/Include" -g3 -pedantic -Wall -Wextra -Wconversion -fmessage-length=0 -std=c++17 -ffunction-sections -c -fno-rtti -MMD -MP -MF"Src/User/Testcases/Test_SD.d" -MT"Src/User/Testcases/Test_SD.o" -o "Src/User/Testcases/Test_SD.o" "../Src/User/Testcases/Test_SD.cpp"
Finished building: ../Src/User/Testcases/Test_SD.cpp
使用的链接器标志
Building target: xxx.elf
Invoking: MCU G++ Linker
arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -L"xxx\Middlewares\ST\STemWin\Lib" -specs=nosys.specs -specs=nano.specs -u_printf_float -T"../STM32F429ZITx_FLASH.ld" -Wl,-Map=output.map -Wl,--gc-sections -fno-exceptions -fno-rtti -o "Giessomat.elf" @"objects.list" -lSTemWin540_CM4_OS_GCC -lm
Finished building target: Giessomat.elf
make --no-print-directory post-build
Generating binary and Printing size information:
已编辑条目
【问题讨论】:
-
看来minimal reproducible example 是有序的。你使用什么编译器和编译标志?
-
是什么导致您期望溢出时出现异常? 我希望它是未定义的行为,但我没有检查标准来验证这个。
-
我怎样才能确保不会因为空闲堆很少而遇到意外行为。如何检查添加向量元素是否失败?
标签: c++