Skip to content

Instantly share code, notes, and snippets.

@BenSYZ
Created July 21, 2023 07:02
Show Gist options
  • Save BenSYZ/5261bb4e08ceb63d76a9d562ed83fc7e to your computer and use it in GitHub Desktop.
Save BenSYZ/5261bb4e08ceb63d76a9d562ed83fc7e to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <signal.h>
#define BYTE sizeof(int8_t)
#define KILOBYTE 1024*BYTE
#define MEGABYTE 1024*KILOBYTE
#define GIGABYTE 1024*MEGABYTE
#define DEFAULT_MALLOC_SIZE 1*GIGABYTE
int* int_array=0;
void sigintHandler(int signum){
if (int_array){
printf("free int_array");
sleep(1);
free(int_array);
}
exit(0);
}
int main(int argc, char* argv[]){
char *endptr=NULL;
int base=10;
unsigned long malloc_size=DEFAULT_MALLOC_SIZE;
int set_value=0;
assert(argc <= 2);
if (argc == 2){
malloc_size=strtoul(argv[1], &endptr , base);
//printf("%c\n", *endptr);
//printf("%ld\n", malloc_size);
switch (*endptr){
case 'K':
malloc_size=malloc_size*KILOBYTE;
break;
case 'M':
malloc_size=malloc_size*MEGABYTE;
break;
case 'G':
malloc_size=malloc_size*GIGABYTE;
break;
case 'k':
malloc_size=malloc_size*KILOBYTE;
break;
case 'm':
malloc_size=malloc_size*MEGABYTE;
break;
case 'g':
malloc_size=malloc_size*GIGABYTE;
break;
default:
break;
}
}
int_array=(int * )malloc(malloc_size);
memset(int_array, set_value, malloc_size);
printf("%.3lf MB (%ld B) has been allocated\n", malloc_size/(1.0*MEGABYTE), malloc_size);
signal(SIGINT, sigintHandler);
while (1){
set_value=rand();
memset(int_array, set_value, malloc_size);
printf("set %p to %d\n", int_array, set_value);
sleep(10);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment