简体   繁体   中英

Linux: brk() error 'Cannot allocate memory'

I'm trying to use the brk() function in a C program. My goal is to use it directly (as part of a larger test) by checking the current program break (pb) with

void *current_break = sbrk(0);

executing a malloc (for testing as malloc should sometimes execute brk if the allocated space is large enough)

void* mallow_return = malloc(1);

and than directly executing brk() by using the current address + an increment (and check if this increase the pb):

int increase = 0x01; 
void * newbreak = current_break + increase;
int return_value = brk(&newbreak);

My problem is, that neither with a large malloc (malloc(5000;)) nor with (aligned or unaligned) brk() call the pb is changed. When checking the errno I get a

Cannot allocate memory! error (as given by strerror(errno)

Can anybody see why I'm not able to increase the program break in anyway?

Thanks for any hints!

(System is: Debian 10 (buster) with kernel 4.19)

Edit: As requested this is the main function with includes:

#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

void main(int argc, char **argv)
{

printf("[+] Get current program break\n");
void *current_break = sbrk(0);
printf("\t[+] Current break point=\t%#x\n", current_break);


printf("[+] Malloc should call brk as well\n");
void* mallow_return = malloc(1);

printf("[+] Check if malloc changes PB\n");
void *after_break = sbrk(0);
printf("\t[+] After malloc pbreak=\t%#x\n", after_break);


int increase = 0x01; 
printf("\t[+] Increasing p-break direclyby %d\n", increase);


void * newbreak = current_break + increase;
printf("\t[+] Setting break point to=\t%#x\n", newbreak);


int return_value = brk(&newbreak);

//check if error was thrown
int errornumber = errno;
if (errornumber != 0)
{
    printf("\t[+] Error: %s!\n", strerror(errornumber)); 
    return -1;
}

//check if pb was set now
printf("\t[?] New program break value?\t%#x\n", sbrk(0));
printf("[?] Return value of brk: %d\n", return_value);

return;
}

(Thanks to @Antii Haapala, who posted this as a comment.)

We need to remove the ampersand here:

 int return_value = brk(&newbreak);

That line should be simply

int return_value = brk(newbreak);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM