[PATCH 2/2] Don't rely on malloc to return NULL for zero size

Anton Lundin glance at acc.umu.se
Thu Dec 11 23:59:12 PST 2014


We rely on samples being NULL if a dc have no samples. Its completely
legal for malloc to return a valid pointer to nowhere for zero sized
malloc, which you can't follow and read what its pointing at. Its only
viable to call free() on.

In other code, if samples is a valid pointer, we dereference it and look
at the first sample.

Signed-off-by: Anton Lundin <glance at acc.umu.se>
---
 dive.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/dive.c b/dive.c
index 8e8330f..4cf532f 100644
--- a/dive.c
+++ b/dive.c
@@ -602,6 +602,14 @@ void copy_samples(struct divecomputer *s, struct divecomputer *d)
 	int nr = s->samples;
 	d->samples = nr;
 	d->alloc_samples = nr;
+	// We expect to be able to read the memory in the other end of the pointer
+	// if its a valid pointer, so don't expect malloc() to return NULL for
+	// zero-sized malloc, do it our selfs.
+	d->sample = NULL;
+
+	if(!nr)
+		return;
+
 	d->sample = malloc(nr * sizeof(struct sample));
 	if (d->sample)
 		memcpy(d->sample, s->sample, nr * sizeof(struct sample));
-- 
2.1.0



More information about the subsurface mailing list