malloc 无法分配内存
malloc unable to allocate memory
我只是不明白为什么 malloc 在这个函数中使用 "Cannot allocate memory" 一直失败:(它触发错误和 return -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;
}
我在主函数中调用该函数为:
circularBuffer_get(buf, -1, (void***)&arr);
注意 buf 分配得很好(我检查了每个值和指针,buf->elCount 的当前值是 1(我也使用 printf 检查了它)。
我也不认为这是我使用的虚拟机的问题,因为其他程序 运行 分配东西很好...
size_t(-1) = 18446744073709551615
您可能 运行 内存不足 :)
我使用的类型size_t是无符号的,传递一个-1作为参数会导致这样的错误
我只是不明白为什么 malloc 在这个函数中使用 "Cannot allocate memory" 一直失败:(它触发错误和 return -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;
}
我在主函数中调用该函数为:
circularBuffer_get(buf, -1, (void***)&arr);
注意 buf 分配得很好(我检查了每个值和指针,buf->elCount 的当前值是 1(我也使用 printf 检查了它)。
我也不认为这是我使用的虚拟机的问题,因为其他程序 运行 分配东西很好...
size_t(-1) = 18446744073709551615
您可能 运行 内存不足 :)
我使用的类型size_t是无符号的,传递一个-1作为参数会导致这样的错误