https://github.com/amid68/xmalloc
The xmalloc project simplifies memory allocation in C by providing a custom wrapper around malloc() that automatically handles memory allocation failures, ensuring programs either succeed in allocating memory or terminate gracefully.
https://github.com/amid68/xmalloc
c malloc memory-allocation
Last synced: about 2 months ago
JSON representation
The xmalloc project simplifies memory allocation in C by providing a custom wrapper around malloc() that automatically handles memory allocation failures, ensuring programs either succeed in allocating memory or terminate gracefully.
- Host: GitHub
- URL: https://github.com/amid68/xmalloc
- Owner: Amid68
- License: mit
- Created: 2024-09-04T14:56:37.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-09-15T17:53:08.000Z (almost 2 years ago)
- Last Synced: 2025-02-24T14:42:09.467Z (over 1 year ago)
- Topics: c, malloc, memory-allocation
- Language: C
- Homepage:
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# xmalloc: Simplifying Memory Allocation in C
This project demonstrates the use of a custom memory allocation function called `xmalloc()` that simplifies the process of dynamic memory allocation in C. The function wraps around `malloc()`, handling error checking and making your code cleaner and easier to maintain.
## Features
- **`xmalloc()`**: A wrapper around `malloc()` that checks for memory allocation failures.
- **Error handling**: If allocation fails, the program prints an error message and exits.
- **Demo Programs**: Two demo programs (`xmalloc-demo-1.c` and `xmalloc-demo-2.c`) showcase the usage of `xmalloc()` and its benefits.
## Files
- `xmalloc.h`: Header file defining the `xmalloc()` macro.
- `xmalloc.c`: Implementation of the `malloc_or_exit()` function.
- `xmalloc-demo-1.c`: A demo showing basic usage of `xmalloc()`.
- `xmalloc-demo-2.c`: A demo simulating memory allocation until failure (memory leak example).
## Usage
### Compilation
To compile the project, use the provided `Makefile`. It will compile the necessary object files and create executables for the demo programs.
```bash
make
```
### Running the Demos
1. **Run `xmalloc-demo-1`:**
```bash
./xmalloc-demo-1
```
**Expected output:**
```
Allocating 1000 bytes
Memory allocated
Memory freed
Allocating 0 bytes
xmalloc-demo-1.c: line 15: malloc() of 0 bytes failed
```
2. **Run `xmalloc-demo-2`:**
```bash
./xmalloc-demo-2
```
**Note:** This program simulates a memory leak and will allocate large amounts of memory until it fails.
### Cleaning Up
To remove the compiled files, use:
```bash
make clean
```