Skip to content

Commit 52924e9

Browse files
committed
Avoid memcpy()-ing 0-length vectors
The C standard (before C23) says that giving invalid pointers, even with length=0, to memcpy() is undefined behaviour. R returns an invalid pointer for vectors of length 0, so avoid calls to memcpy() altogether in such cases.
1 parent f231b5d commit 52924e9

File tree

2 files changed

+2
-2
lines changed

2 files changed

+2
-2
lines changed

src/dogroups.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,7 @@ SEXP growVector(SEXP x, const R_len_t newlen)
535535
if (isNull(x)) error(_("growVector passed NULL"));
536536
PROTECT(newx = allocVector(TYPEOF(x), newlen)); // TO DO: R_realloc(?) here?
537537
if (newlen < len) len=newlen; // i.e. shrink
538-
switch (TYPEOF(x)) {
538+
if (len) switch (TYPEOF(x)) {
539539
case RAWSXP: memcpy(RAW(newx), RAW(x), len*SIZEOF(x)); break;
540540
case LGLSXP: memcpy(LOGICAL(newx), LOGICAL(x), len*SIZEOF(x)); break;
541541
case INTSXP: memcpy(INTEGER(newx), INTEGER(x), len*SIZEOF(x)); break;

src/utils.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ SEXP copyAsPlain(SEXP x) {
222222
}
223223
const int64_t n = XLENGTH(x);
224224
SEXP ans = PROTECT(allocVector(TYPEOF(x), n));
225-
switch (TYPEOF(x)) {
225+
if (n) switch (TYPEOF(x)) {
226226
case RAWSXP:
227227
memcpy(RAW(ans), RAW(x), n*sizeof(Rbyte));
228228
break;

0 commit comments

Comments
 (0)