i just don't get why malloc keeps failing with "Cannot allocate memory" in this function: (it triggers the perror and return -1)
EDIT: size_t is an unsigned type, of course it won't work when passing -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).
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作为参数传递将导致此类错误
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.