diff options
author | Egor Tensin <Egor.Tensin@gmail.com> | 2023-05-18 11:17:46 +0200 |
---|---|---|
committer | Egor Tensin <Egor.Tensin@gmail.com> | 2023-05-29 23:38:39 +0200 |
commit | ad82be9beabfc3346c72095db558d5be629891e5 (patch) | |
tree | 430fd4797158fc3ab608cd1f14bcba5569d574dd /src | |
parent | file: rework file_read (diff) | |
download | cimple-ad82be9beabfc3346c72095db558d5be629891e5.tar.gz cimple-ad82be9beabfc3346c72095db558d5be629891e5.zip |
fix realloc usage
Remember, this is always a mistake:
ptr = realloc(ptr, size);
You still need to free() the original ptr if realloc fails.
Diffstat (limited to 'src')
-rw-r--r-- | src/file.c | 13 |
1 files changed, 9 insertions, 4 deletions
@@ -69,11 +69,12 @@ char *my_readlink(const char *path) char *buf = NULL; while (1) { - buf = realloc(buf, current_size); - if (!buf) { + char *tmp_buf = realloc(buf, current_size); + if (!tmp_buf) { log_errno("realloc"); goto free; } + buf = tmp_buf; ssize_t res = readlink(path, buf, current_size); if (res < 0) { @@ -111,9 +112,13 @@ int file_read(int fd, char **_contents, size_t *_size) size_t size = 0; while (1) { - contents = realloc(contents, alloc_size); - if (!contents) + char *tmp_contents = realloc(contents, alloc_size); + if (!tmp_contents) { + log_errno("realloc"); + free(contents); return -1; + } + contents = tmp_contents; ssize_t read_size = read(fd, contents + size, alloc_size - size - 1); |