title: C - realloc error: corrupted size vs prev_size
body: <p>Could someone please explain the error?<br>
  I was getting the error until, on a whim, I changed the line from:</p>
  
  <pre><code>char *tmp = realloc(str, sizeof(char)*length);
  // to                                           added 1
  char *tmp = realloc(str, sizeof(char) * length + 1);
  </code></pre>
  
  <p>I thought that multiplying <code>sizeof(char)</code> by length would reallocate a new memory area of <code>size=sizeof(char)*length</code>. I'm not understanding why adding 1 fixes the problem.</p>
  
  <pre><code>    void edit_print(char *inputStr, size_t space_size) {
        size_t ch_position = 0;
        size_t space_column_count = 0;
        size_t num_spaces_left = 0;
        while ((inputStr[ch_position] != '\0')) {
          if ((inputStr[ch_position] == '\t') &amp;&amp; (space_size !=0)) {
            num_spaces_left = (space_size-(space_column_count % space_size));
            if (ch_position == 0 || !(num_spaces_left)) {
              for (size_t i=1; i &lt;= space_size; i++) {
                putchar(' ');
                space_column_count++;
              }
              ch_position++;
            } else {
              for (size_t i=1; i &lt;= num_spaces_left; i++) {
                putchar(' ');
                space_column_count++;
              }
              ch_position++;
            }
          } else {
            putchar(inputStr[ch_position++]);
            space_column_count++;
          }
        }
        printf("\n");
      }
  
          int main(int argc, char *argv[]) {
            size_t space_size_arg = 3; 
            int inputch;
            size_t length = 0;
            size_t size = 10;
            char *str = realloc(NULL, sizeof(char) * size);
            printf("Enter stuff\n");
  
            while ((inputch = getchar()) != EOF) {
              if (inputch == '\n') {
                str[length++] = '\0';
  
                //changed line below
                char *tmp = realloc(str, sizeof(char) * length + 1);
  
                if (tmp == NULL) {
                  exit(0);
                } else {
                  str = tmp;
                }
                edit_print(str, space_size_arg);
                length = 0;
              } else {
                str[length++] = inputch;
                if (length == size) {
                  char *tmp = realloc(str, sizeof(char) * (size += 20));
                  if (tmp == NULL) {
                    exit(0);
                  } else {
                    str = tmp;
                  }
                }
              }
            }
            free(str);
            return 0;
          }
  </code></pre>
  
  <p>EDIT: the error message I original got was the one in the heading of this post. After making the changes suggested by chux, the error is "realloc(): invalid next size: *hexnumber**"</p>