Skip to content

Instantly share code, notes, and snippets.

@benyanke
Created May 5, 2017 17:19
Show Gist options
  • Save benyanke/acce412c018bcc29be32d10b0112171c to your computer and use it in GitHub Desktop.
Save benyanke/acce412c018bcc29be32d10b0112171c to your computer and use it in GitHub Desktop.
Memory allocation example
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
// Wait [secs] seconds
void waitFor (unsigned int secs) {
unsigned int retTime = time(0) + secs; // Get finishing time.
while (time(0) < retTime); // Loop until it arrives.
}
in t main(int argc, char** argv) {
// MB of memory to try to allocate (-1 = unlimited)
int max = -1;
// Number of seconds to hold the memory before exiting and releasing memory
int wait = 2;
// Internal variables, no need to change
int mb = 0;
char* buffer;
if(argc > 1)
max = atoi(argv[1]);
// Allocate memory until either max is reached or it can not be allocated
while((buffer=malloc(1024*1024)) != NULL && mb != max) {
memset(buffer, 0, 1024*1024);
mb++;
printf("Allocated %d MB\n", mb);
}
// Hold the memory for [wait] seconds before exiting the program and releasing memory
printf("Allocation complete\nHolding %d mb of memory for %d seconds\n", mb, wait);
waitFor(wait);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment