0

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...

8
  • For starters this statement size_t retVal = (count >= 0 ? count : buf->elCount); does not make sense. Commented Jul 1, 2017 at 12:03
  • 1
    size_t is an unsigned type. So -1 becomes a huge value when assigned to a size_t. Commented Jul 1, 2017 at 12:04
  • oh god that's right why am i so dumb? Commented Jul 1, 2017 at 12:05
  • also @VladfromMoscow it's a sizeof(void*), which has sense Commented Jul 1, 2017 at 12:06
  • @NokiStrawby I advice to delete the question update your code and ask the question with the new updated code. Commented Jul 1, 2017 at 12:07

2 Answers 2

1
size_t(-1) = 18446744073709551615 

You might have just run out of memory :)

Sign up to request clarification or add additional context in comments.

Comments

0

the type size_t i used is unsigned, and passing a -1 as an argument will lead to such errors

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.