Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem is not how you're freeing, but how you're creating the array. Consider this:</p> <pre><code>uniqueWords[numUniqueWords] = malloc(strlen(word)); uniqueWords[numUniqueWords] = word; ... word = strtok(NULL, " ,.-!?()\"0123456789"); </code></pre> <p>There are several issues here:</p> <p><code>word = strtok()</code>: what strtok returns is not something that you can free, because it has not been malloc'ed. ie it is not a copy, it just points to somewhere inside the underlying large string (the thing you called strtok with first). </p> <p><code>uniqueWords[numUniqueWords] = word</code>: this is not a copy; it just assigns the pointer. the pointer which is there before (which you malloc'ed) is overwritten.</p> <p><code>malloc(strlen(word))</code>: this allocates too little memory, should be strlen(word)+1</p> <p>How to fix:</p> <p>Option A: copy properly </p> <pre><code>// no malloc uniqueWords[numUniqueWords] = strdup(word); // what strdup returns can be free'd </code></pre> <p>Option B: copy properly, slightly more verbose</p> <pre><code>uniqueWords[numUniqueWords] = malloc(strlen(word)+1); strcpy(uniqueWords[numUniqueWords], word); // use the malloc'ed memory to copy to </code></pre> <p>Option C: don't copy, don't free</p> <pre><code>// no malloc uniqueWords[numUniqueWords] = word; // not a copy, this still points to the big string // don't free this, ie don't free(list[i]) in free_memory </code></pre> <p><em>EDIT</em> As other have pointed out, this is also problematic:</p> <pre><code> char *uniqueWords[numTotalWords]; </code></pre> <p>I believe this is a GNU99 extension (not even C99), and indeed you cannot (should not) free it. Try <code>char **uniqueWords = (char**)malloc(sizeof(char*) * numTotalWords)</code>. Again the problem is not the free() but the way you allocate. You are on the right track with the free, just need to match every free with a malloc, or with something that says it is equivalent to a malloc (like strdup).</p>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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