C & C++

C & C++

Made by DeepSource

Pointer returned from a function is dereferenced on LHS of an assignement CXX-W1230

Anti-pattern
Minor

When a function returns a pointer to dynamically allocated memory, it is the responsibility of the caller to free that memory after it is no longer needed. But if the caller deferences such a pointer on the left-hand side of an assignment expression, the caller loses the oppurtunity to free the memory.

To avoid this issue, it is recommended to store the returned pointer in a temporary variable, use it as needed, and then free the memory before exiting the caller function.

Bad practice

int* ret(int* num) {
    return num;
}
int* ret_leak() {
    return (int*)malloc(sizeof(int));
}
int main() {
    int t = 10;
    *ret(&t) = 20;
    // We forget the returned pointer here, 
    // which may leak memory.
    *ret_leak() = 20;
    printf("%d", t);
}

Recommended

int* ret(int* num) {
    return num;
}
int* ret_leak() {
    return (int*)malloc(sizeof(int));
}
int main() {
    int t = 10;
    *ret(&t) = 20;
    int* rl = ret_leak();
    // The pointer be stored in a local variable,
    // allowing us to free or reuse it if needed.
    *rl = 20;
    printf("%d", t);
    printf("%d", *rl);
}