title: Local variables and memory in c
body: <p>I'm somewhat new to <code>C</code> and am wondering about certain things about memory allocation. My function is as follows:</p>
  
  <pre><code>size_t count_nwords(const char* str) {
      //char* copied_str = strdup(str);  // because 'strtok()' alters the string it passes through
      char copied_str[strlen(str)];
      strcpy(copied_str, str);
      size_t count = 1;
  
      strtok(copied_str, " ");
      while(strtok(NULL, " ") != 0) {
          count++;
      }
  
      //free(copied_str);
  
      return count;
  }
  </code></pre>
  
  <p>This function counts the amount of words in a string (the delimiter is a space, ie "<code></code>"). I do not want the string passed in argument to be modified.</p>
  
  <p>I have two questions:</p>
  
  <ol>
  <li>Should the <code>strdup()</code> way (which is the commented part in the code) be preferred over the <code>strcpy()</code> one? My understanding is that <code>strcpy()</code> is sufficient and faster, but I am not certain.</li>
  <li>Since no memory is allocated for the <code>size_t</code> value to be returned (it's a local variable), should it be done in order to ensure the function is robust? Or is using <code>size_t nwords = count_nwords(copied_input);</code> completely safe and will always properly get the returned value?</li>
  </ol>
  
  <p>Thank you!</p>
  
  <p>EDIT: I've accepted the only answer that concerned my questions precisely, but I advise reading the other answers as they provide good insights regarding errors I had made in my code.</p>