我有一个简单的C语言的大脑解释器,它在scan-build中产生以下警告:

$ scan-build gcc -Wall -g -std=c99 main.c
scan-build: Using '/usr/bin/clang' for static analysis
main.c:14:11: warning: Assigned value is garbage or undefined
        c = *(program + instruction_index);
          ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
scan-build: 1 bug found.

下面是我的程序的最小版本,它展示了这种行为:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <alloca.h>

void eval_program(char *program) {
    int program_len = strlen(program);
    int data_index = 0, instruction_index = 0;

    char c;
    while (instruction_index < program_len) {
        c = *(program + instruction_index);

        switch (c) {
        case '>':
            data_index++;
            instruction_index++;
            break;
        default:
            instruction_index++;
            break;
        }
    }
}

char *read_string(int file_descriptor) {
    char *s = NULL;
    int total_bytes_read = 0;

    int BUFFER_SIZE = sizeof(char) * 1024;
    char *temp_buffer = alloca(BUFFER_SIZE);

    int bytes_read;
    // Not bothering checking the return code from read or realloc for
    // errors, because it doesn't affect scan-build's output.
    while ((bytes_read = read(file_descriptor, temp_buffer, BUFFER_SIZE))) {
        s = realloc(s, total_bytes_read + bytes_read);
        memcpy(s + total_bytes_read, temp_buffer, bytes_read);
        total_bytes_read += bytes_read;
    }

    s = realloc(s, total_bytes_read + 1);
    s[total_bytes_read] = '\0';

    return s;
}

int main() {
    char *program = read_string(0); // read from stdin
    eval_program(program);
    free(program);

    return 0;
}

使用gcc和-Wall -Wextra编译时,此程序不会生成任何警告,因此为什么访问字符串垃圾或未定义?这个程序在我的测试中运行良好。
这是一个最小的例子,没有错误检查mallocread,但是the warning still occurs if I use error checking。如果我用realloc替换malloc,也会出现警告。

最佳答案

可以将read_string()函数缩减为:

char *read_string(int file_descriptor) {
    char *s = NULL;

    s = malloc(1);
    //memset(s,0,1);
    s[0] = 0;

    return s;
}

如果在memset()调用中添加注释,则警告消失。因此,我认为静态分析器在这种情况下是错误的。

10-06 14:36