为什么访问以null结尾的字符串给出'garbage或undefined'?

Wil*_*hes 4 c clang clang-static-analyzer

我在C中有一个简单的brainfuck解释器,它产生以下警告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.
Run Code Online (Sandbox Code Playgroud)

这是我的程序的最小版本,表现出这种行为:

#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;
}
Run Code Online (Sandbox Code Playgroud)

使用GCC编译时,此程序不会生成任何警告-Wall -Wextra,那么为什么要访问字符串garbage或undefined?该程序在我的测试中运行良好.

这是一个没有错误检查一个小例子,malloc或者read,但如果我使用错误检查的警告仍然出现.如果我更换realloc,也会发出警告malloc.

nos*_*nos 5

您可以将read_string()函数减少到:

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

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

    return s;
}
Run Code Online (Sandbox Code Playgroud)

如果您在memset()调用中发表评论,警告就会消失.因此,我得出结论,静态分析仪在这种情况下是错误的.