Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <malloc.h>
- #include <stdarg.h>
- // Create simple array type.
- typedef struct { unsigned length, *values; } array;
- // Get length of array.
- void length(array *arr) {
- unsigned i = 0;
- // Keep going until we reach the terminator.
- // This poses a buffer overflow vulnerability.
- // The terminator might exist after the data in memory, meaning that
- // we could potentially overwrite memory after the data.
- // Don't rely on this value in a legit program, otherwise you're going
- // to be in for a bad time.
- for (; arr->values[i] != '\0'; i++);
- arr->length = i;
- }
- // Initialize an array.
- void Array(array *arr, ...) {
- va_list vlist;
- va_start(vlist, arr);
- // We're not going to free this malloc which will become a
- // memory leak.
- // Even though we're allocating between 8 to 16 KiB of memory
- // we are unlikely to be using all of it so it's not a problem.
- // Unless this is running on a machine with no internal storage and
- // has less than 8 KiB of RAM left to run this program, then this
- // shouldn't be an issue.
- arr->values = malloc(sizeof(array *) * 2048);
- unsigned i = 0, value = va_arg(vlist, unsigned);
- while (value != 0) {
- arr->values[i] = value;
- i++;
- value = va_arg(vlist, unsigned);
- }
- // Initialize the length of our array.
- length(arr);
- // End off the variable argument list.
- va_end(vlist);
- }
- void find_missing(array *arr) {
- for (unsigned i = 0; i < arr->length; i++) {
- // If the next value in the array is not the next character in
- // the ASCII sequence, then print the missing value and break
- // free from the loop.
- if (arr->values[i + 1] != arr->values[i] + 1) {
- fprintf(stdout, "%c is missing!\n", arr->values[i] + 1);
- break;
- }
- }
- }
- int main() {
- array array1, array2;
- Array(&array1, 'a', 'b', 'd', 'e', 'f', 'g');
- Array(&array2, 'n', 'p');
- find_missing(&array1);
- find_missing(&array2);
- // This region is used to free memory just before the program gets
- // terminated. This is useless since that memory will end up getting
- // freed when the program is terminated.
- free(array1.values);
- free(array2.values);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement