-[NSInputStream read:maxLength:] throws an exception saying length is too big, but it isn't

不羁的心 提交于 2019-12-01 05:29:17

Your problem is a so called "stack overflow" (you might have heard this before).

Your method allocates a buffer on the stack using a variable length array:

uint8_t buf[bufferSizeNumber];

When the size of the buffer is so large that it overflows the size of the current stack the behavior is undefined. Undefined behavior might result in a crash or just work as expected: just what you are observing.

512kB is a huge buffer, especially on iOS where background threads get a stack of exactly this size.

You should allocate it on the heap:

NSInteger bufferSizeNumber = 524288;
NSMutableData *myBuffer = [NSMutableData dataWithLength:bufferSizeNumber];

uint8_t *buf = [myBuffer mutableBytes];
unsigned int len = 0;

len = [_stream read:buf maxLength:bufferSizeNumber];
// more code ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!