#include #include #include #define SIZE 20 typedef struct s1 { long ts; char location[SIZE]; int temp; } Reading; // -------------------------------------------------- int main(int argc, char** argv) { // Allocate Reading *pointer = (Reading*)malloc(sizeof(Reading)); // Check if allocation worked if ( ! pointer ) { fprintf(stderr,"Out of memory\n"); return 1; } long time = 20; int temp = 67; // Use the structure pointer->ts = time; pointer->temp = temp; printf("Sample is (%ld,%d)\n", pointer->ts, pointer->temp); // Free free(pointer); // Common bug 1: Accessing memory that has been freed already // pointer is now dangling, could cause silent bug printf("BUG! BEFORE NULL! Sample is (%ld,%d)\n", pointer->ts, pointer->temp); // making sure that error will cause crash! pointer = NULL; // Good programming practice to set unused pointers to NULL printf("BUG! AFTER NULL! Sample is (%ld,%d)\n", pointer->ts, pointer->temp); // Common bug 2: memory leaks pointer = (Reading*)malloc(sizeof(Reading)); // Allocate chunk 1 pointer = (Reading*)malloc(sizeof(Reading)); // Allocate chunk 2 free(pointer); // Can never free the memory allocated for chunk 1 // The above problems get tricky with functions // When one function allocates space and other functions // are supposed to free it later on return 0; }