Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Created January 21, 2015 23:24
Show Gist options
  • Save Wilfred/edbbdd8b61d3aef1d52a to your computer and use it in GitHub Desktop.
Save Wilfred/edbbdd8b61d3aef1d52a to your computer and use it in GitHub Desktop.
Unexpected clang build warning
#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;
}
}
}
void *realloc_or_die(void *ptr, size_t size) {
void *p = realloc(ptr, size);
if (p == NULL) {
fprintf(stderr, "Out of memory! Exiting.");
exit(1);
}
return p;
}
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;
while ((bytes_read = read(file_descriptor, temp_buffer, BUFFER_SIZE))) {
if (bytes_read == -1) {
fprintf(stderr,
"Could not read from file descriptor %d, exiting.\n",
file_descriptor);
exit(1);
}
s = realloc_or_die(s, total_bytes_read + bytes_read);
memcpy(s + total_bytes_read, temp_buffer, bytes_read);
total_bytes_read += bytes_read;
}
s = realloc_or_die(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;
}
$ scan-build gcc -Wall -g -std=c99 main.c
scan-build: Using '/usr/bin/clang' for static analysis
main.c:13:11: warning: Assigned value is garbage or undefined
c = *(program + instruction_index);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
scan-build: 1 bug found.
scan-build: Run 'scan-view /tmp/scan-build-2015-01-21-232411-5285-1' to examine bug reports.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment