FDD-book/examples/part-01/ch04-a-first-look-at-the-c-programming-language/lab-memory-crash/lab1_fixed.c
Edson Brandi 6e6dac94fe Add book companion files under examples/
Organize companion code and materials by book part:

  part-01/      Foundations
  part-02/      Kernel & driver fundamentals
  part-03/      Character & block devices
  part-04/      Networking & storage
  part-05/      Buses & advanced topics
  part-06/      Debugging & performance
  part-07/      Real-world drivers
  appendices/   Supplementary material
  README.md     Overview and build instructions
2026-04-25 16:51:00 +00:00

33 lines
558 B
C

/*
* lab1_fixed.c - corrected version of lab1_crash.c.
*
* Allocates memory for a struct data on the heap, checks for
* allocation failure, writes into the structure safely, prints the
* value, and frees the memory before exiting.
*/
#include <stdio.h>
#include <stdlib.h> /* malloc, free */
struct data {
int value;
};
int
main(void)
{
struct data *ptr;
ptr = malloc(sizeof(struct data));
if (ptr == NULL) {
printf("Allocation failed!\n");
return (1);
}
ptr->value = 42;
printf("Value: %d\n", ptr->value);
free(ptr);
return (0);
}