Back to all reviewers

Validate before dereference

tensorflow/tensorflow
Based on 5 comments
Other

Always check that pointers, optional values, and results of type casts are valid before dereferencing or using them. This prevents null pointer exceptions, undefined behavior, and potential crashes in production.

Null Handling Other

Reviewer Prompt

Always check that pointers, optional values, and results of type casts are valid before dereferencing or using them. This prevents null pointer exceptions, undefined behavior, and potential crashes in production.

For pointers obtained from operations or external sources:

// Before accessing a pointer's members
if (value.getDefiningOp() != nullptr) {
  // Now safe to use value.getDefiningOp()->getResult(0)
}

For optional values, verify presence before access:

auto shared_library_dir = FindDispatchOption(options, num_options, kDispatchOptionSharedLibraryDir);
if (shared_library_dir.HasValue()) {
  shared_library_dir_opt.emplace(std::any_cast<const char*>(shared_library_dir.Value()));
}

For dynamic casts, check success before using the result:

auto input_type = input_value.getType().dyn_cast<RankedTensorType>();
if (!input_type) {
  op->emitOpError("Input type not ranked tensor");
  return nullptr;
}

When designing APIs, preserve nullability expectations to maintain compatibility:

// Check parameters that might be null rather than requiring non-null
if (run_metadata != nullptr) {
  // Only use run_metadata when it's provided
}
5
Comments Analyzed
Other
Primary Language
Null Handling
Category

Source Discussions