简体   繁体   中英

C language. Logic error: The left operand of '-' is a garbage value

I have the following code, but in this line of code I have warning x[i] = (rhs[i] - x[i - 1]) / b; , compiler is telling me that rhs[i] is a garbage value. Why it's happend? And how to remove this warning?

double* getFirstControlPoints(double* rhs, const int n) {
    double *x;
    x = (double*)malloc(n * sizeof(double));
    double *tmp; // Temp workspace.
    tmp = (double*)malloc(n * sizeof(double));

    double b = 2.0;
    x[0] = rhs[0] / b;
    for (int i = 1; i < n; i++) // Decomposition and forward substitution.
    {
        tmp[i] = 1 / b;
        b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
        x[i] = (rhs[i] - x[i - 1]) / b; //The left operand of '-' is a garbage value
    }
    for (int i = 1; i < n; i++) {
        x[n - i - 1] -= tmp[n - i] * x[n - i]; // Backsubstitution.
    }
    free(tmp);
    return x;
}

在此输入图像描述

在此输入图像描述

All compiler warnings and calling getFirstControlPoints you may see on screenshots.

You need a check to make sure you have at least 4 points in the points array because this loop (line 333):

for (NSInteger i = 1 ; i < n - 1 ; ++i) {
    // initialisation stuff
}

will not execute at all for n = 0, 1, 2.

Assume that points has 3 objects in it, At line 311 you set n to the count - 1 ie n == 2

Then the loop condition is i < 2 - 1 ie i < 1 .

I think you need the loop condition to be i < n

if points.count is 0 or 1 you are facing some problems, because then, n is -1 or 0, and you access rhs[n-1]; and you malloc n* bytes;

maybe that can be the problem. that you put some rangechecks int o the code?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM