Skip to content

Commit c170413

Browse files
committed
check for creating strings that are too large
1 parent c11568c commit c170413

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

stringdtype/stringdtype/src/static_string.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,10 @@ npy_string_newsize(const char *init, size_t size,
120120
return 0;
121121
}
122122

123+
if (size > NPY_MAX_STRING_SIZE) {
124+
return -1;
125+
}
126+
123127
_npy_static_string_u *to_init_u = ((_npy_static_string_u *)to_init);
124128

125129
if (size > NPY_SHORT_STRING_MAX_SIZE) {
@@ -155,6 +159,10 @@ npy_string_newemptysize(size_t size, npy_packed_static_string *out)
155159
return 0;
156160
}
157161

162+
if (size > NPY_MAX_STRING_SIZE) {
163+
return -1;
164+
}
165+
158166
_npy_static_string_u *out_u = (_npy_static_string_u *)out;
159167

160168
if (size > NPY_SHORT_STRING_MAX_SIZE) {

stringdtype/stringdtype/src/static_string.h

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ extern const npy_packed_static_string *NPY_NULL_STRING;
3333
// check if *to_init* is NULL or if the internal buffer is non-NULL, undefined
3434
// behavior or memory leaks are possible if this function is passed a pointer
3535
// to a an unintialized struct, a NULL pointer, or an existing heap-allocated
36-
// string. Returns -1 if malloc fails. Returns 0 on success.
36+
// string. Returns -1 if allocating the string would exceed the maximum
37+
// allowed string size or exhaust available memory. Returns 0 on success.
3738
int
3839
npy_string_newsize(const char *init, size_t size,
3940
npy_packed_static_string *to_init);
@@ -60,7 +61,8 @@ npy_string_dup(const npy_packed_static_string *in,
6061
// internal buffer is non-NULL, undefined behavior or memory leaks are
6162
// possible if this function is passed a pointer to a an unintialized struct,
6263
// a NULL pointer, or an existing heap-allocated string. Returns 0 on
63-
// success. Returns -1 if malloc fails. Returns 0 on success.
64+
// success. Returns -1 if allocating the string would exceed the maximum
65+
// allowed string size or exhaust available memory. Returns 0 on success.
6466
int
6567
npy_string_newemptysize(size_t size, npy_packed_static_string *out);
6668

stringdtype/tests/test_stringdtype.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,3 +700,9 @@ def test_null_roundtripping(dtype):
700700
arr = np.array(data, dtype=dtype)
701701
assert data[0] == arr[0]
702702
assert data[1] == arr[1]
703+
704+
705+
def test_string_too_large_error():
706+
arr = np.array(["a", "b", "c"], dtype=StringDType())
707+
with pytest.raises(MemoryError):
708+
arr * (2**63 - 2)

0 commit comments

Comments
 (0)