[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[PATCH] tail: avoid theoretically undefined behavior
From: |
Jim Meyering |
Subject: |
[PATCH] tail: avoid theoretically undefined behavior |
Date: |
Wed, 28 Dec 2011 18:56:49 +0100 |
Can anyone name a real system on which forming a pointer like this,
"buffer + (size_t)(-1)" actually provokes a trap or some other real problem?
>From 6e00315bf290310895036fce979a7e0210871b63 Mon Sep 17 00:00:00 2001
From: Jim Meyering <address@hidden>
Date: Wed, 28 Dec 2011 18:30:50 +0100
Subject: [PATCH] tail: avoid theoretically undefined behavior
* src/tail.c (start_lines): Do not form potentially-invalid address.
Use safe_read's return value as a pointer offset only after
ensuring that it is not SAFE_READ_ERROR (size_t)(-1).
Spotted by coverity.
Also, move declaration of "p" to be closer to first use.
---
src/tail.c | 5 +++--
1 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/src/tail.c b/src/tail.c
index 4581845..5d86da2 100644
--- a/src/tail.c
+++ b/src/tail.c
@@ -848,9 +848,7 @@ start_lines (const char *pretty_filename, int fd, uintmax_t
n_lines,
while (1)
{
char buffer[BUFSIZ];
- char *p = buffer;
size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
- char *buffer_end = buffer + bytes_read;
if (bytes_read == 0) /* EOF */
return -1;
if (bytes_read == SAFE_READ_ERROR) /* error */
@@ -859,8 +857,11 @@ start_lines (const char *pretty_filename, int fd,
uintmax_t n_lines,
return 1;
}
+ char *buffer_end = buffer + bytes_read;
+
*read_pos += bytes_read;
+ char *p = buffer;
while ((p = memchr (p, '\n', buffer_end - p)))
{
++p;
--
1.7.8.1.391.g2c2ad
- [PATCH] tail: avoid theoretically undefined behavior,
Jim Meyering <=