title: Incorrect checksum for freed object on malloc
body: <p>I get an </p>
  
  <pre><code>malloc: *** error for object 0x1001012f8: incorrect checksum for freed object
          - object was probably modified after being freed.
          *** set a breakpoint in malloc_error_break to debug
  </code></pre>
  
  <p>error in the following function:</p>
  
  <pre><code>char* substr(const char* source, const char* start, const char* end) {
      char *path_start, *path_end, *path;
  
      int path_len, needle_len = strlen(start);
  
      path_start = strcasestr(source, start);
      if (path_start != NULL) {
          path_start += needle_len;
          path_end = strcasestr(path_start, end);
          path_len = path_end - path_start;
          path = malloc(path_len + 1);
          strncpy(path, path_start, path_len);
          path[path_len] = '\0';
      } else {
          path = NULL;
      }
  
      return path;
  }
  </code></pre>
  
  <p>How can I make this work? When I rewrite the function to allocate the memory using <code>path[path_len + 1]</code> it works just fine.</p>
  
  <p>Now, the part I don't understand is, that I never even call <code>free</code> in any point of my application, as every allocated memory is needed for the program until it exists (which, AFAIK will invalidate every allocated memory anyway?!)</p>
  
  <p>So, how can a freed object be corrupt if I never free one?</p>
  
  <p>The function is called in this one:</p>
  
  <pre><code>char *read_response(int sock) {
      int bytes_read;
      char *buf = (char*)malloc(BUF_SIZE);
      char *cur_position = buf;
  
      while ((bytes_read = read(sock, cur_position, BUF_SIZE)) &gt; 0) {
          cur_position += bytes_read;
          buf = realloc(buf, sizeof(buf) + BUF_SIZE);
      }
  
      int status = atoi(substr(buf, "HTTP/1.0 ", " "));
  </code></pre>
  
  <p>There is the <code>realloc</code>, am I using that wrong? I want to read the complete server response, so I have to reallocate after every iteration, don't I?</p>