~sircmpwn/ctools

c77ee19899c575d76bc18b8c08a604961d1906db — Stefan Tatschner 1 year, 21 days ago bf90378
head: Unify error path and fix memory leak

$ meson test -C build --verbose  head
ninja: Entering directory `/home/rumpelsepp/Projects/vendor/ctools/build'
ninja: no work to do.
should_read_from_stdin
=================================================================
==399092==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 8192 byte(s) in 1 object(s) allocated from:
    #0 0x7f28f131ece8 in __interceptor_calloc /build/gcc/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:153
    #1 0x55a9faa60582 in head ../src/head.c:32
    #2 0x55a9faa60ae9 in main ../src/head.c:82
    #3 0x7f28f0708ee2 in __libc_start_main (/usr/lib/libc.so.6+0x26ee2)

SUMMARY: AddressSanitizer: 8192 byte(s) leaked in 1 allocation(s).
FAIL
1 files changed, 22 insertions(+), 7 deletions(-)

M src/head.c
M src/head.c => src/head.c +22 -7
@@ 16,20 16,29 @@ usage(void)
static int
head(const char *path, int length, bool header, bool newline)
{
	FILE *file;
	char *buf = NULL;
	FILE *file = NULL;
	int r = 1;

	if (path[0] == '-' && path[1] == '\0') {
		file = stdin;
	} else {
		if ((file = fopen(path, "r")) == NULL) {
			perror(path);
			return 1;
			goto out;
		}
	}

	ssize_t n;
	size_t buf_size = BUFSIZ;
	int curr_line = 0;
	char *buf = calloc(sizeof(char), buf_size);

	buf = calloc(sizeof(char), buf_size);
	if (!buf) {
		perror("mem");
		goto out;
	}

	if (header) {
		printf("%s==> %s <==\n", newline? "\n" : "", path);
	}


@@ 43,15 52,21 @@ head(const char *path, int length, bool header, bool newline)
			ssize_t o = printf("%s", buf);
			if (o < 0) {
				perror("write");
				fclose(file);
				return 1;
				goto out;
			}
			offs += o;
		}
		curr_line++;
	}
	fclose(file);
	return 0;

	r = 0;

out:
	if (file) {
		fclose(file);
	}
	free(buf);
	return r;
}

int