Our Test Programs
The source snippets given in the following overviews the most basic problems with dynamic memory allocation and usage. These examples are closely related to the examples given in the lecture Programmieren 2.
Source file: error01.c, access without allocation
#include <stdlib.h> #include <stdio.h> int main() { long *ptr; fprintf(stderr, "uninitialized pointer: %p\n", ptr); fprintf(stderr, "trying to assign 15 \n"); *ptr = 15; // Error: memory could not be allocated! return 0; }
Source file: error02.c, access before allocation
#include <stdlib.h> #include <stdio.h> int main() { long *ptr; fprintf(stderr, "uninitialized pointer: %p\n", ptr); fprintf(stderr, "assign 15 to ptr[5]:\n"); ptr[5] = 23; // error .. access to uninitialized pointer if (!(ptr = malloc(10 * sizeof(long)))) { fprintf(stderr, "Error: memory could not be allocated!\n"); exit(-1); } printf("%ld\n", ptr[5]); return 0; }
Source file: error03.c, no validation of allocation
#include <stdlib.h> #include <stdio.h> #include <limits.h> int main() { long *ptr; unsigned long size = LONG_MAX * 1.5; ptr = malloc(size); //what happens when malloc returns 0? fprintf(stderr, "Pointer to malloc(size): %p\n", ptr); ptr[0] = 1; free(ptr); return 0; }
Source file: error04.c, wrong size for allocation
#include <stdlib.h> #include <stdio.h> int main() { long *ptr, i; ptr = malloc(10); /* incomplete specification of memory size */ fprintf(stderr, "malloc(10) pointer: %p\n", ptr); ptr = malloc(10 * sizeof(char)); /* incomplete specification */ for (i = 0; i < 10; ++i) ptr[i] = 1; fprintf(stderr, "malloc(10 * sizeof(char)) pointer: %p\n", ptr); free(ptr); return 0; }