{"id":6285,"date":"2024-03-09T00:01:05","date_gmt":"2024-03-09T08:01:05","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=6285"},"modified":"2024-02-24T16:57:57","modified_gmt":"2024-02-25T00:57:57","slug":"the-alloca-function","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=6285","title":{"rendered":"The <em>alloca()<\/em> Function"},"content":{"rendered":"<p>Any memory allocated in a function is retained when the function leaves, unless you first free it. This rule applies to all memory allocation functions &mdash; except one.<br \/>\n<!--more--><br \/>\nOf course, memory allocated in the <em>main()<\/em> function is freed when it returns (the program exits). This is the reason why I&#8217;m often lazy and forget to free memory at the end of the <em>main()<\/em> function, a sin for which I repent. But an exception to the memory allocation\/freeing rule is the <em>alloca()<\/em> function.<\/p>\n<p>Like an <em>auto<\/em> variable, the <em>alloca()<\/em> function&#8217;s scope is local to the function it&#8217;s used in: Memory is allocated, but released when the next function is called. It&#8217;s not released upon return from the function (though this aspect may be undefined), but when you call another function the memory <em>alloca()<\/em> allocated is gone.<\/p>\n<p>To demonstrate the <em>alloca()<\/em> function, I first wrote code that uses <em>malloc()<\/em> to allocate and use a buffer:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2024_03_09-Lesson-a.c\" rel=\"noopener\" target=\"_blank\">2024_03_09-Lesson-a.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n\r\nchar *astring(void)\r\n{\r\n    const int size = 12;\r\n    char *a;\r\n    int x;\r\n\r\n    a = malloc(size+1);\r\n    for( x=0; x&lt;size; x++ )\r\n        *(a+x) = 'A';\r\n    *(a+x) = '\\0';\r\n\r\n    printf(\"Allocated string: '%s'\\n\",a);\r\n\r\n    return a;\r\n}\r\n\r\nvoid header(void)\r\n{\r\n    puts(\"After temporary allocation\");\r\n}\r\n\r\nint main()\r\n{\r\n    char *alpha;\r\n    puts(\"Temporary allocation\");\r\n    alpha = astring();\r\n\r\n    header();\r\n    printf(\"Allocated string: '%s'\\n\",alpha);\r\n    free(alpha);\r\n\r\n    return 0;\r\n}<\/pre>\n<p>The <em>astring()<\/em> function allocates 13 bytes of <em>char<\/em> storage, which is assigned characters and output. I don&#8217;t test the allocation for failure, which is something you must do in your own code. Here, allocating 13 bytes shouldn&#8217;t be an issue.<\/p>\n<p>The <em>main()<\/em> function saves the pointer returned from <em>astring()<\/em> in variable <code>alpha<\/code>. Before outputting the string, the <em>header()<\/em> function is called. Yes, this is weird code, but it&#8217;s designed to demonstrate how the <em>alloca()<\/em> function works: A second function must be called to free the memory (according to the docs). Here&#8217;s the ouput:<\/p>\n<p><code>Temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<br \/>\nAfter temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<\/code><\/p>\n<p>To update the code with <em>alloca()<\/em> instead of <em>malloc()<\/em> these changes are made: <code>stdlib.h<\/code> is replaced by <code>alloca.h<\/code>; <em>malloc()<\/em> is replaced by <em>alloca()<\/em>; and the <em>free()<\/em> statement is removed from the <em>main()<\/em> function. You can <a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2024_03_09-Lesson-b.c\" rel=\"noopener\" target=\"_blank\">click here<\/a> to view the updated version of the code on GitHub.<\/p>\n<p>Here is the output when <em>clang<\/em> builds the program:<\/p>\n<p><code>Temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<br \/>\nAfter temporary allocation<br \/>\nAllocated string: ''<\/code><\/p>\n<p>The string is zapped after the call to the <em>header()<\/em> function.<\/p>\n<p>Being curious, I ran a few tests to confirm how the <em>alloca()<\/em> function works. If I don&#8217;t call the <em>header()<\/em> function, the allocated string is output:<\/p>\n<p><code>Temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<br \/>\nAfter temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<\/code><\/p>\n<p>I had assumed that the allocated storage was released when the function call returned. The <em>man<\/em> page says that <em>alloca()<\/em>&#8216;s memory is released when another function is called, which is why the original code called the <em>header()<\/em> function.<\/p>\n<p>When I tested the code with the GNU compiler, the memory doesn&#8217;t seem to be released. Here is the program&#8217;s output when built with <em>gcc<\/em>:<\/p>\n<p><code>Temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<br \/>\nAfter temporary allocation<br \/>\nAllocated string: 'AAAAAAAAAAAA'<\/code><\/p>\n<p>Though it looks like the allocated memory is intact, if you attempt to <em>free()<\/em> the pointer&#8217;s address you get an invalid pointer message as the program runs. This error message appears for programs built by both <em>clang<\/em> and <em>gcc<\/em>. So I guess the memory is released when built with <em>gcc<\/em> but something quirky is keeping the contents around. It could just be my own system.<\/p>\n<p>I can&#8217;t think of an application where the <em>alloca()<\/em> function is necessary, especially given that memory can always be freed. Yet this function is available in some C libraries and must have some purpose.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here&#8217;s a function you can use when you need to forget to free memory on purpose. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=6285\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-6285","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/6285","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=6285"}],"version-history":[{"count":5,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/6285\/revisions"}],"predecessor-version":[{"id":6296,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/6285\/revisions\/6296"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=6285"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=6285"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=6285"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}