[(NSInputStream *)流读取:buf maxLength:1024];返回非常巨大的价值

时间:2015-04-29 06:28:07

标签: ios sockets nsinputstream

在代码行中

->NSInteger len = [(NSInputStream *)stream read:buf   maxLength:1024]; 

我从这个方法得到非常巨大的len值,如:(18446744073709551615)

并崩溃

  

由于未捕获的异常终止应用程序' NSMallocException',原因: - [NSConcreteMutableData appendBytes:length:]:无法为长度分配内存(18446744073709551615)

case NSStreamEventHasBytesAvailable:

{



NSMutableData* lobjReadData = [[NSMutableData alloc] init];

NSNumber* lnumBytesRead;

uint8_t buf[1024];



NSUInteger lintReadingBufferLength = 0;

NSUInteger lintTotalBufferReadedlength = 0;

NSUInteger lintPreviousBufferReadedlength = 0;

NSUInteger lintSeenIndex = 0;



while ([(NSInputStream*)stream hasBytesAvailable])

{



    lintReadingBufferLength = [(NSInputStream *)stream read:buf

                                                  maxLength:1024];



    // some times i am getting very huge vaqlue of lintReadingBufferLength like

    //18446744073709551615

    //crashes here with crash log -> Terminating app due to uncaught exception 'NSMallocException', reason: '*** -[NSConcreteMutableData appendBytes:length:]: unable to allocate memory for length (18446744073709551615)'



    lintTotalBufferReadedlength += lintReadingBufferLength;



    if(lintReadingBufferLength)

    {

        [lobjReadData appendBytes:(const void *)buf

                           length:lintReadingBufferLength];



        // bytesRead is an instance variable of type NSNumber.

        lnumBytesRead = [NSNumber numberWithInteger:

                         [lnumBytesRead integerValue]+lintReadingBufferLength];





        NSArray* larrayOfBytes = [self arrayOfBytesFromData:lobjReadData];







        for (NSInteger lintIndexCounter = lintPreviousBufferReadedlength; lintIndexCounter < lintTotalBufferReadedlength;

             lintIndexCounter++)

        {

            NSObject* lobjByte = [larrayOfBytes objectAtIndex:lintIndexCounter];



            NSString* lstrMessage = [NSString stringWithFormat:@"%@",lobjByte];



            //doing some stuff here

        }



        lintPreviousBufferReadedlength = lintTotalBufferReadedlength;

    }

    else if(0 == lintReadingBufferLength)

    {



    }

    else

    {

        SLog(@"no buffer!");

    }



}



// SLog(@"--------------------------------------");



break;

}

2 个答案:

答案 0 :(得分:1)

184467440737095516150xffffffffffff,它是最大无符号64位整数值,但它也等同于-1作为64位有符号整数。

如果您查看[NSInputStream read:maxLength:]的参考文件,则说:

  

返回值

     

表示操作结果的数字:

     
      
  • 正数表示读取的字节数;

  •   
  • 0表示已到达缓冲区的末尾;

  •   
  • 负数表示操作失败。

  •   

因此操作失败,您将该值视为无符号值。

答案 1 :(得分:0)

read:方法的返回类型是什么?是NSUInteger吗?它不是。它是NSInteger。那么为什么它返回有符号整数而不是无符号整数?这是read:方法的文档中的内容。阅读该文档,然后您应该知道,使用NSUInteger而不是NSInteger创建的您的代码实际上是一个不合理的大数字。