https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111394

            Bug ID: 111394
           Summary: Warning about uninitialized memory that is actually
                    initialized
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: aiya64bits at gmail dot com
  Target Milestone: ---

#include <stdio.h>
#include <stdlib.h>

int memoized_cut_rod_aux(const int p[], int n, int c, int r[]) {
    if (r[n] >= 0)
        return r[n];

    int q = p[n - 1];
    if (!n) {
        q = 0;
    } else {
        for (int i = 1; i <= n / 2; ++i) {
            const int v = p[i - 1] + memoized_cut_rod_aux(p, n - i, c, r) - c;
            if (v > q)
                q = v;
        }
    }
    r[n] = q;
    return q;
}

int memoized_cut_rod(const int p[], int n, int c) {
    int result;

    int *const r = malloc((n + 1) * sizeof(int));
    if (!r) {
        fprintf(stderr, "Out of memory.\n");
        exit(1);
    }

    for (int i = 0; i < n + 1; ++i)
        r[i] = -1;

    result = memoized_cut_rod_aux(p, n, c, r);
    free(r);
    return result;
}

The above code when compiled with "gcc -Wall -O3 -o rod_cutting rod_cutting.c"
gives the following warning:

In function ‘memoized_cut_rod_aux’,
    inlined from ‘memoized_cut_rod’ at rod_cutting.c:95:17:
rod_cutting.c:59:14: warning: ‘*r_30 + _122’ may be used uninitialized
[-Wmaybe-uninitialized]
   59 |         if (r[n] >= 0)
      |             ~^~~

But all the elements of r are initialized to -1 in the loop in
memoized_cut_rod. I got this warning with GCC 13.2.1 and then got the same
warning with the trunk branch.

Reply via email to