From 34c100361b0d11ad18d4a2e113d4b97aae770a0d Mon Sep 17 00:00:00 2001 From: Riccardo Schirone Date: Feb 11 2022 12:31:15 +0000 Subject: [PATCH 1/2] Do not use alloca inside a loop --- diff --git a/modules/ROOT/pages/programming-languages/C.adoc b/modules/ROOT/pages/programming-languages/C.adoc index ce92257..e81250a 100644 --- a/modules/ROOT/pages/programming-languages/C.adoc +++ b/modules/ROOT/pages/programming-languages/C.adoc @@ -676,6 +676,13 @@ Otherwise, call `malloc`. When exiting the function, check if `malloc` had been called, and free the buffer as needed. +Remember that memory allocated on the stack through `alloca` +is released at the end of the function and not at the end of +the block where it is defined, thus it is reccommended to not +call `alloca` inside a loop. In this regard, VLA behaves better, +considering the memory allocated with VLA is released at the end +of the block that defines them. + [[sect-Defensive_Coding-C-Allocators-Arrays]] === Array Allocation From 5c5f165d9253bd5dc86cdfb31a5a59e6a727d2a5 Mon Sep 17 00:00:00 2001 From: Riccardo Schirone Date: Feb 11 2022 12:31:16 +0000 Subject: [PATCH 2/2] Notify about mixing VLA and alloca --- diff --git a/modules/ROOT/pages/programming-languages/C.adoc b/modules/ROOT/pages/programming-languages/C.adoc index e81250a..6dcd443 100644 --- a/modules/ROOT/pages/programming-languages/C.adoc +++ b/modules/ROOT/pages/programming-languages/C.adoc @@ -681,7 +681,8 @@ is released at the end of the function and not at the end of the block where it is defined, thus it is reccommended to not call `alloca` inside a loop. In this regard, VLA behaves better, considering the memory allocated with VLA is released at the end -of the block that defines them. +of the block that defines them. Do not mix VLA and `alloca` though, +otherwise this behaviour is not guaranteed for VLA either! [[sect-Defensive_Coding-C-Allocators-Arrays]] === Array Allocation