bzhu
bzhu

Reputation: 954

Why didn't Valgrind detect Uninitialised value was used

#include <stdlib.h>
int* matvec(int A[][3], int* x, int n) {
    int i, j;
    int* y = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            y[i] += A[i][j] * x[j];
        }
    }
    free(y);
}

void main() {
    int a[3][3] = {
        {0, 1, 2},
        {2, 3, 4},
        {4, 5, 6}
    };
    
    int x[3] = {1, 2, 3};
    matvec(a, x, 3);
}

I detect memory problem by below command: valgrind --tool=memcheck --leak-check=full --track-origins=yes ./a.out it gives output:

==37060== Memcheck, a memory error detector
==37060== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==37060== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==37060== Command: ./a.out
==37060== 
==37060== 
==37060== HEAP SUMMARY:
==37060==     in use at exit: 0 bytes in 0 blocks
==37060==   total heap usage: 1 allocs, 1 frees, 12 bytes allocated
==37060== 
==37060== All heap blocks were freed -- no leaks are possible
==37060== 
==37060== For lists of detected and suppressed errors, rerun with: -s
==37060== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Question is: Why the valgind didn't detect the problem that: y array is used as uninitialized

Upvotes: 0

Views: 27

Answers (1)

rob mayoff
rob mayoff

Reputation: 385500

From the Valgrind User Manual §4.2.2 Use of uninitialised values:

A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.

You are starting with some uninitialized memory, keeping it uninitialized, and then freeing it. You are not using it in an externally-visible way, such as by using it in an if condition or passing it to a system call.

Upvotes: 2

Related Questions