I've been trying to learn a bit about dynamic allocation in my noobish way, and I decided to see what would happen if I deliberately tried to cram too much data into a memory block that is too small to contain it all. Ironically the program seems to function correctly, printing out the full array, even though I've tried to make it overload. I can't figure out why.
Output:Code:/* Dynamic memory allocation */ #include <stdio.h> #include <stdlib.h> int main() { char size[5]; // Array deliberately set too small int *memory_block; int i; char word[] = "abcdefghijklmnopqrs"; char c; /* Allocate memory defined by char array 'size' */ memory_block = malloc(sizeof(size)); /* Check for allocation failure */ if(memory_block == NULL) { printf("Allocation Failed.\n"); exit(EXIT_FAILURE); }else printf("Memory Allocated.\n"); /* Copy data stored in 'word' into 'memory_block' */ for(i = 0; word[i]; i++) { memory_block[i] = word[i]; printf("%c\n", memory_block[i]); } /* Return memory to heap */ free(memory_block); /* Exit */ printf("Press 'q' to exit:"); if((c = _getch()) == 'q') return 0; }
Memory Allocated
a
b
c
d
e
f
............
s
Press 'q' to exit: