c - I am getting "pointer being freed was not allocated" -
i reading stdin. since not know length of read, have use malloc.
i getting pointer being freed not allocated
sometimes, happens before free(final), before free(tmp).
i check both pointers correctly non null after creating them , before making free. can pin point doing wrong ?
total_size = 0; final = (char *)malloc(sizeof(char) * 1); if (!final) { printf("error allocating memory final\n"); return (null); } while ((ret = read(0, buf, buf_size)) > 0) { tmp = (char *)malloc(sizeof(char) * ft_strlen(final)); if (!tmp) { printf("error allocating memory tmp\n"); return (null); } strcpy(tmp, final); if (final) free(final); buf[ret] = '\0'; total_size = total_size + ret; final = (char *)malloc(sizeof(char) * total_size); if (!final) { printf("error allocating memory final\n"); return (null); } final = strcat(tmp, buf); if (tmp) free(tmp); } return (final);
this problem you:
final = (char *)malloc(sizeof(char) * total_size);
[...]
final = strcat(tmp, buf);
you leaking allocated memory , aliasing *final
, *tmp
. can thereafter free one of them, must not afterward free other without first reassigning point valid dynamically-allocated block.
overall, looks going lot of unnecessary trouble tmp
. far can tell, you're trying increase size of block final
points, , that's realloc()
for:
size_t desired_size = total_size + ret + 1; // need space terminator char *tmp = realloc(final, desired_size); if (!tmp) { perror("error allocating more memory final"); // realloc() not free pointer on failure; @ least glibc's doesn't free(final); return (null); } final = tmp; buf[ret] = '\0'; // strcat wasteful if know destination string's length strcpy(final + total_size, buf); total_size += ret;
the reallocated block may or may not start in same place original, realloc()
takes care of copying data if necessary.
Comments
Post a Comment