Why is there access to a null-terminated string giving "garbage or undefined"?

I have a simple brainfuck interpreter in C that throws the following warning in 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.

Here is the smallest version of my program that exhibits this behavior:

#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 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;
}

This program does not generate any warnings when compiling with GCC and -Wall -Wextraso why access file junk or undefined? The program works great when testing.

This is a minimal example without error checking mallocor read, but a warning still occurs if I use error checking . A warning also occurs if replaced reallocby malloc.

+4
2

read_string() :

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

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

    return s;
}

memset(), . , .

+5

.

clang-analyzer LLVM, . 22289.

+2

All Articles