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_tis an unsigned type. So-1becomes a huge value when assigned to asize_t.