Skip to content

Instantly share code, notes, and snippets.

@kssreeram
Created July 2, 2021 04:08
Show Gist options
  • Save kssreeram/5a512bb6b262756cab654b46223a5e97 to your computer and use it in GitHub Desktop.
Save kssreeram/5a512bb6b262756cab654b46223a5e97 to your computer and use it in GitHub Desktop.
How to avoid UB in this code?
//
// Adding zero to a null-pointer is undefined behavior!
//
// In the following code, String a is dynamically sized array of chars.
// UB is triggerred when appending an empty string to an freshly initialized String.
// See line 50.
//
// What is the recommended approach to avoid this error?
//
// Compile and run with:
// clang -fsanitize=undefined append-ub.c
// ./a.out
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *data;
int size;
int capacity;
} String;
void reserve(String *a, int required) {
if (a->size + required <= a->capacity) {
return;
}
a->capacity = a->size + required;
a->data = realloc(a->data, a->capacity);
}
void append(String *a, char *s) {
int n = strlen(s);
reserve(a, n);
memcpy(a->data + a->size, s, n);
a->size += n;
}
void show(String *a) {
printf("STR: '");
fwrite(a->data, 1, a->size, stdout);
printf("'\n");
}
int main() {
String a;
memset(&a, 0, sizeof(a));
show(&a);
append(&a, "");
show(&a);
free(a.data);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment