Should memory allocation check if the pointer is NULL?
@shakedregev is already working on this.
Since Oct 7, 2025.
- Dominant language
- C++
- Stars
- 84
- Forks
- 13
- PR merge metrics
- No merged PRs in 30d
Description
At several places in sparse matrix classes we check if the pointer is nullptr before we allocate memory and assign it to that pointer. Here is one such example:
if (d_col_data_ == nullptr) {
mem_.allocateArrayOnDevice(&d_col_data_, n_ + 1);
}
if (d_row_data_ == nullptr) {
mem_.allocateArrayOnDevice(&d_row_data_, nnz_current);
}
if (d_val_data_ == nullptr) {
mem_.allocateArrayOnDevice(&d_val_data_, nnz_current);
}
Perhaps we should consider throwing exception when the pointer is not nullptr? This way potential bugs may remain undetected, because if the pointer is not a null, this does not necessarily mean that the allocated memory is of the size we need. In such case we may end up with undefined behavior such as writing past the end of array. More defensive programming would be to send an error message and throw an exception in situations like this.
CC @rothpc @maksud
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.