简体   繁体   English

malloc无法分配内存

[英]malloc unable to allocate memory

i just don't get why malloc keeps failing with "Cannot allocate memory" in this function: (it triggers the perror and return -1) 我只是不明白为什么malloc在此函数中始终显示“无法分配内存”失败:(它触发错误并返回-1)

EDIT: size_t is an unsigned type, of course it won't work when passing -1 编辑:size_t是一个无符号类型,当然在传递-1时将不起作用

int circularBuffer_get(circularBuffer_t *buf, size_t count, void ***retArray) { 
    size_t retVal = (count >= 0 ? count : buf->elCount);
    if (retVal == 0) return 0;

    /* ALloco l'array di ritorno */
    void **retArr = malloc(sizeof(void*) * retVal);
    if(!retArr) {perror("Allocating return value"); return -1; }
    memset(retArr, 0, sizeof(void*) * retVal);

    int i, j = 0; /* Percorro gli elementi da estrarre */
    for (i = (buf->bufCursor - retVal + buf->bufSize) % buf->bufSize; i < retVal; i = (i+1) % buf->bufSize ) {
        /* Estraggo l'elemento */
        retArr[j] = buf->buffer[i];

        /* Libero lo slot nel buffer */
        buf->buffer[i] = NULL;
        j++;
    }

    /* Aggiorno il numero di elementi nel buffer */
    buf->elCount -= retVal;

    *retArray = retArr;
    return retVal;
}

i am calling that function at the main function as: 我在主要功能上调用该功能为:

circularBuffer_get(buf, -1, (void***)&arr);

notice that buf is allocated fine (i checked each value and pointer and the current value of buf->elCount is 1 (i checked that using a printf, too). 注意,buf分配得很好(我检查了每个值和指针,并且buf-> elCount的当前值为1(我也使用printf进行了检查)。

I don't think that's a problem with the virtual machine i'm using, either, as other programs run just fine allocating stuff... 我也不认为我正在使用的虚拟机有问题,因为其他程序可以很好地分配东西...

size_t(-1) = 18446744073709551615

您可能刚用完内存:)

我使用的size_t类型是无符号的,将-1作为参数传递将导致此类错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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