【发布时间】:2015-03-20 15:26:36
【问题描述】:
我有一个简单的 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 编译时不会产生任何警告,那么为什么访问字符串垃圾或未定义?该程序在我的测试中运行良好。
这是一个没有错误检查 malloc 或 read 的最小示例,但 the warning still occurs if I use error checking。如果我将realloc 替换为malloc,也会出现警告。
【问题讨论】:
-
我真的没看出程序有什么问题,你读过
clang的文档中的警告是什么意思吗? -
@nos 是的,同样的错误。请注意,
temp_buffer永远不会传递给realloc。 -
@user3121023 是的,但正如评论所说,修复并不会消除此错误。我试图保持我的例子简短,但see this version for the same warning even when checking for errors.
-
在我看来,被指控的代码没问题,所以它看起来像是误报。你用的是最新版的
scan-build吗? -
如果检查
malloc()或realloc()的返回值是否为空,错误报告是否会改变?
标签: c clang clang-static-analyzer