Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am learning linux resource control using
setrlimit
and
getrlimit
. The idea is to limit the maximum amount of memory that can be used for a given process:
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
// Define and object of structure
// rlimit.
struct rlimit rl;
// First get the limit on memory
getrlimit (RLIMIT_AS, &rl);
printf("\n Default value is : %lld\n", (long long int)rl.rlim_cur);
// Change the limit
rl.rlim_cur = 100;
rl.rlim_max = 100;
// Now call setrlimit() to set the
// changed value.
setrlimit (RLIMIT_AS, &rl);
// Again get the limit and check
getrlimit (RLIMIT_AS, &rl);
printf("\n Default value now is : %lld\n", (long long int)rl.rlim_cur);
// Try to allocate more memory than the set limit
char *ptr = NULL;
ptr = (char*) malloc(65536*sizeof(char));
if(NULL == ptr)
printf("\n Memory allocation failed\n");
return -1;
printf("pass\n");
free(ptr);
return 0;
The above code limit the memory to 100 bytes (both soft and hard). However, the malloc
still returns without error. Is there anything wrong with the code? The output I got is:
Default value is : -1
Default value now is : 100
No, there's nothing wrong with your code. You're only wrong to assume that RLIMIT_AS
has an immediate effect on malloc()
. In a nutshell, the latter (usually, there are many variations) allocates its backing memory in chunks from heap with brk()
or on-demand-mapped pages with mmap()
and then carves those chunks into individual allocations. The chances are there was already enough space allocated in heap to satisfy your malloc()
call, whereas your new RLIMIT_AS
would affect only subsequent calls for brk()
and mmap()
. All in all, it is perfectly normal.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.