{"id":34560,"date":"2023-03-31T00:05:45","date_gmt":"2023-03-30T18:35:45","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/"},"modified":"2023-03-31T00:05:45","modified_gmt":"2023-03-30T18:35:45","slug":"solved-realloc-not-working-in-my-program-any-ideas-why","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/","title":{"rendered":"[Solved] Realloc not working in my program, any ideas why?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-75690757\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"75690757\" data-parentid=\"75690532\" data-score=\"2\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>In your function <code>int huffman(node_t *huff, int n)<\/code> you try to <code>realloc()<\/code> the <code>huff<\/code> pointer but in C we pass variables by value so you only receive a copy of the pointer.  This means caller retains the original pointer and the <code>realloc()<\/code> memory is lost when you return from the function.  You need to pass in a <code>**huff<\/code>:<\/p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;getopt.h&gt;\n\nconst int expand_size = 4;\nint length = 4;\n\ntypedef struct {\n    char w[2]; \/\/word\n    int v; \/\/value\n    int d; \/\/direction\n    char b; \/\/binary\n} node_t;\n\nint maxi(node_t *huff, int n) {\n    int maxi = huff[0].v;\n    for(int i=0;i&lt;n;i++)\n        if(huff[i].v&gt;maxi)\n            maxi=huff[i].v;\n    return maxi;\n}\n\nint mini(node_t *huff, int n) {\n    int mini = maxi(huff, n);\n    int w=0;\n    for(int i=0;i&lt;n;i++)\n        if(huff[i].v&lt;=mini &amp;&amp; huff[i].v &gt;=0){\n            w=i;\n            mini=huff[i].v;\n        }\n    return w;\n}\n\nint huffman(node_t **huff, int n){\n    int j=1;\n    int i=1;\n    while (i!=n){\n        int index1=mini(*huff, n);\n        int value1=(*huff)[index1].v;\n        (*huff)[index1].v=-1;\n        int index2=mini(*huff, n);\n        int value2=(*huff)[index2].v;\n        (*huff)[index2].v=-1;\n        (*huff)[index1].d = n;\n        (*huff)[index2].d = n;\n        (*huff)[index1].b = '1';\n        (*huff)[index2].b = '0';\n        if ( n == length ){\n            node_t *temp = realloc(*huff, (length + expand_size) * sizeof *temp);\n            if(!temp) {\n                printf(\"realloc failed\\n\");\n                exit(1);\n            }\n            *huff=temp;\n            for ( int h = length; h &lt; length + expand_size; h++){\n                (*huff)[h].v = 0;\n            }\n            length += expand_size;\n        }\n        (*huff)[n].v=value1 + value2;\n        (*huff)[n].w[0]=j+'0';\n        j++;\n        i=i+2;\n        n++;\n    }\n    return n;\n}\n\nint main( int argc, char** argv) {\n    int opt;\n    char *file = NULL;\n    char steps = 0;\n    char compression_level = 0;\n    while ((opt = getopt (argc, argv, \"o:f:v\")) != -1) {\n        switch (opt) {\n            case 'f':\n                file = optarg;\n                break;\n\n            case 'v':\n                steps = 1;\n                break;\n\n            case 'o':\n                compression_level = atof ( optarg );\n                break;\n\n            case '?':\n                printf(\"Z\u0142e parametry wywo\u0142ania\");\n                return 1;\n                break;\n        }\n    }\n    if(!file) {\n        printf(\"file is required\\n\");\n        return EXIT_FAILURE;\n    }\n    FILE *read = fopen(file, \"r\");\n    node_t *huff = malloc(length * sizeof *huff);\n    int counter = 0;\n    for (int i=0; i&lt;length; i++)\n        huff[i].v = 0;\n\n    if (read == NULL) {\n        printf (\"file can't be opened \\n\");\n        return 1;\n    }\n    if(compression_level == 1){\n        int c;\n        while ((c = fgetc(read)) != EOF ){\n            for (int i=0; i&lt;length; i++){\n                if (!huff[i].v){\n                    huff[i].w[0] = c;\n                    huff[i].v++;\n                    counter++;\n                    break;\n                }\n                if (huff[i].w[0]== c){\n                    huff[i].v++;\n                    break;\n                }\n                if (i == length - 1){\n                    node_t *temp = realloc(huff, (length + expand_size) * sizeof *temp);\n                    if(!temp) {\n                        printf(\"relloc failed\\n\");\n                        exit(EXIT_FAILURE);\n                    }\n                    huff=temp;\n                    for (int j = length; j &lt; length + expand_size; j++)\n                        huff[j].v = 0;\n                    length += expand_size;\n                }\n            }\n        }\n    }\n    int n = huffman(&amp;huff, counter);\n    for(int i=0; i&lt;counter; i++){\n        int l=i;\n        if(compression_level == 1)\n            printf(\"%c: \", huff[i].w[0]);\n        if(compression_level == 2)\n            printf(\"%c%c: \", huff[i].w[0], huff[i].w[1]);\n        while (l!=n-1){\n            printf(\"%c\", huff[l].b);\n            l = huff[l].d;\n        }\n        printf(\"\\n\");\n    }\n    if (steps == 1) {\n        for (int i=0; i&lt;counter; i++){\n            if( huff[i].w[0] == 10)\n                printf(\"'%d' 'LINE FEED' occured %d razy\\n\", huff[i].w[0], huff[i].v);\n        }\n        printf(\"array length %d\\n\", length);\n        printf(\"how many nodes %d\\n\", n);\n        printf(\"how many primary nodes %d\\n\", counter);\n    }\n    free(huff);\n    fclose(read);\n    return 0;\n}\n<\/code><\/pre>\n<p>I also reduced scope of variables, checked return value of <code>realloc()<\/code>, checked that <code>file<\/code> is set.  Here is the valgrind summary after the change:<\/p>\n<pre><code>==2612036== HEAP SUMMARY:\n==2612036==     in use at exit: 0 bytes in 0 blocks\n==2612036==   total heap usage: 41 allocs, 41 frees, 53,016 bytes allocated\n==2612036== \n==2612036== All heap blocks were freed -- no leaks are possible\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">5<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Realloc not working in my program, any ideas why? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] In your function int huffman(node_t *huff, int n) you try to realloc() the huff pointer but in C we pass variables by value so you only receive a copy of the pointer. This means caller retains the original pointer and the realloc() memory is lost when you return from the function. You need to &#8230; <a title=\"[Solved] Realloc not working in my program, any ideas why?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\" aria-label=\"More on [Solved] Realloc not working in my program, any ideas why?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[324,2162,1355],"class_list":["post-34560","post","type-post","status-publish","format-standard","hentry","category-solved","tag-c","tag-realloc","tag-structure"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Realloc not working in my program, any ideas why? - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Realloc not working in my program, any ideas why? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] In your function int huffman(node_t *huff, int n) you try to realloc() the huff pointer but in C we pass variables by value so you only receive a copy of the pointer. This means caller retains the original pointer and the realloc() memory is lost when you return from the function. You need to ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-30T18:35:45+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Realloc not working in my program, any ideas why?\",\"datePublished\":\"2023-03-30T18:35:45+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\"},\"wordCount\":93,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"c++\",\"realloc\",\"structure\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\",\"name\":\"[Solved] Realloc not working in my program, any ideas why? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2023-03-30T18:35:45+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Realloc not working in my program, any ideas why?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Realloc not working in my program, any ideas why? - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Realloc not working in my program, any ideas why? - JassWeb","og_description":"[ad_1] In your function int huffman(node_t *huff, int n) you try to realloc() the huff pointer but in C we pass variables by value so you only receive a copy of the pointer. This means caller retains the original pointer and the realloc() memory is lost when you return from the function. You need to ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/","og_site_name":"JassWeb","article_published_time":"2023-03-30T18:35:45+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Realloc not working in my program, any ideas why?","datePublished":"2023-03-30T18:35:45+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/"},"wordCount":93,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["c++","realloc","structure"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/","url":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/","name":"[Solved] Realloc not working in my program, any ideas why? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2023-03-30T18:35:45+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-realloc-not-working-in-my-program-any-ideas-why\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Realloc not working in my program, any ideas why?"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/34560","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=34560"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/34560\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=34560"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=34560"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=34560"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}