Don't rely on malloc to return NULL for zero size

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@acc.umu.se>
Signed-off-by: Dirk Hohndel <dirk@hohndel.org>
This commit is contained in:
Anton Lundin 2014-12-12 08:59:12 +01:00 committed by Dirk Hohndel
parent 46bd71a184
commit bf20c251ab

8
dive.c
View file

@ -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 ourselves.
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));