]> git.proxmox.com Git - libgit2.git/commitdiff
Fix a bug in gitfo_read_file()
authorRamsay Jones <ramsay@ramsay1.demon.co.uk>
Sat, 27 Dec 2008 18:56:16 +0000 (18:56 +0000)
committerShawn O. Pearce <spearce@spearce.org>
Tue, 30 Dec 2008 15:32:16 +0000 (07:32 -0800)
In particular, when asked to read an empty file, this function
calls malloc() with a zero size allocation request. Standard C
says that the behaviour of malloc() in this case is implementation
defined.

[C99, 7.20.3 says "... If the size of the space requested is zero,
the behavior is implementation-defined: either a null pointer is
returned, or the behavior is as if the size were some nonzero
value, except that the returned pointer shall not be used to
access an object."]

Finesse the issue by over-allocating by one byte. Setting the extra
byte to '\0' may also provide a useful sentinel for text files.

Signed-off-by: Ramsay Jones <ramsay@ramsay1.demon.co.uk>
Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
src/fileops.c

index caa7d9e0c8f8671cf8b8c9c16eb18d31ca4802d8..e6e4e04556df092bce179810d25ce5330b34d8d5 100644 (file)
@@ -53,14 +53,14 @@ int gitfo_read_file(gitfo_buf *obj, const char *path)
 {
        git_file fd;
        off_t len;
-       void *buff;
+       unsigned char *buff;
 
        assert(obj && path && *path);
 
        if ((fd = gitfo_open(path, O_RDONLY)) < 0)
                return GIT_ERROR;  /* TODO: error handling */
 
-       if (((len = gitfo_size(fd)) < 0) || ((buff = malloc(len)) == NULL)) {
+       if (((len = gitfo_size(fd)) < 0) || ((buff = malloc(len+1)) == NULL)) {
                gitfo_close(fd);
                return GIT_ERROR;  /* TODO: error handling */
        }
@@ -70,6 +70,7 @@ int gitfo_read_file(gitfo_buf *obj, const char *path)
                free(buff);
                return GIT_ERROR;  /* TODO: error handling */
        }
+       buff[len] = '\0';
 
        gitfo_close(fd);