Note that there are some explanatory texts on larger screens.

plurals
  1. POmemory leak for simple program, how can I free allocs?
    primarykey
    data
    text
    <p>I am learning C, and am have a problem finding out how i can free my malloc()'s.</p> <p>The program runs correctly.. but im Using valgrind and it is coming up with 8 allocs and 5 frees. I need to be able to free 3 more. I commented where I believe which I am not freeing but I am not sure of a solution.</p> <p>Is there a way I can free up those allocs, or do I need to consider re-writing the tokenizer()?</p> <p>Here is the code to the whole file.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; char *substr(const char *s, int from, int nchars) { char *result = (char *) malloc((nchars * sizeof(char))+1); strncpy(result, s+from, nchars); return result; } /** Extracts white-space separated tokens from s. @param s A string containing 0 or more tokens. @param ntokens The number of tokens found in s. @return A pointer to a list of tokens. The list and tokens must be freed by the caller. */ char **tokenize(const char *s, int *ntokens) { int fromIndex = 0; int toIndex = 0; char **list; int finalCount = *ntokens; int count = 0; list = malloc(*ntokens * sizeof(char*)); while ( count &lt; finalCount) { char *m = strchr(s,' '); toIndex = m - s; if(toIndex &gt;= 0) { list[count] = substr(s,fromIndex,toIndex); // This substr() gets free'ed from main() s = substr(s, toIndex+1, strlen(s)); // I believe This is where I am making extra mallocs that are not being freed count++; } else { list[count] = substr(s,fromIndex,strlen(s)); // This substr() gets free'ed from main() count++; } } return list; } int main(int argc, char **argv) { char **list; char *string = "terrific radiant humble pig"; int count = 4; // Hard-Coded list = tokenize(string, &amp;count); for (int i=0;i&lt;count;i++) { printf("list[%d] = %s\n", i, list[i]); } // Free mallocs()'s for (int i=0;i&lt;count;i++) { free(list[i]); } // Free List free(list); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload