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

前端 未结 1 387
小蘑菇
小蘑菇 2021-01-13 11:49

I use an NSInputStream to read data from a file. It will crash if maxLength is greater than 49152.

When it crashes -- sometimes, but not e

相关标签:
1条回答
  • 2021-01-13 12:44

    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 ...
    
    0 讨论(0)
提交回复
热议问题