Objective C 中的意外循环
我有这样的代码:
unsigned int k=(len - sizeof(MSG_INFO));
NSLog(@"%d",k);
for( unsigned int ix = 0; ix < k; ix++)
{
m_pOutPacket->m_buffer[ix] = (char)(pbuf[ix + sizeof(MSG_INFO)]);
}
问题是,当:
len = 0 and sizeof(MSG_INFO)=68;
k=-68;
这个条件进入 for 循环并持续无限次。
I have this code:
unsigned int k=(len - sizeof(MSG_INFO));
NSLog(@"%d",k);
for( unsigned int ix = 0; ix < k; ix++)
{
m_pOutPacket->m_buffer[ix] = (char)(pbuf[ix + sizeof(MSG_INFO)]);
}
The problem is, when:
len = 0 and sizeof(MSG_INFO)=68;
k=-68;
This condition gets into the for loop and is continuing for infinite times.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码显示:
unsigned int k
。所以 k 不是 -68,而是无符号
。这使得 ka 变得非常大,基于 4 字节 int< /a>,这将是 4294967210。这显然比 0 大很多,所以你的for
循环需要一段时间才能达到这个高度,尽管它会最终终止。您认为它是-86的原因是,当您使用像 NSLog 这样的函数打印它时,它没有关于传入参数的直接知识,它决定如何处理参数,基于格式字符串,作为第一个参数提供。
您正在呼叫:
这:
这告诉
NSLog
将参数视为signed int (%d)
。您应该这样做:以便 NSLog 将参数视为它的类型:
unsigned (%u)
。 请参阅 NSLog 文档。就目前情况而言,我预计您的缓冲区会溢出,当循环运行时会浪费内存并且应用程序会崩溃。
经过反思,我相信 @FreeAsInBeer 是正确的,并且您不想在这种情况下迭代 for 循环,并且您可以通过使用有符号整数来解决此问题。但是,在我看来,检查
len > 会更好。 sizeof(MSG_INFO)
如果不是这种情况,则以不同的方式处理。我能想到的大多数情况下,如果我未能读取消息的足够信息,我不想在 for 循环之后执行任何处理......Your code says:
unsigned int k
. So k isn't -68, it'sunsigned
. This makes k a very big number, based around a 4 byte int, it would be 4294967210. This is obviously quite a lot more than 0, so it's going to take yourfor
loop a while to get that high, although it would terminate eventually.The reason you think that it's -86, is that when you print it out with a function like
NSLog
, it has no direct knowledge about the arguments passed in, it determines how to treat the arguments, based around the format string, supplied as the first argument.You're calling:
This:
This tells
NSLog
to treat the argument as asigned int (%d)
. You should be doing this:So that NSLog treats the argument as the type that it is:
unsigned (%u)
. See the NSLog documentation.As it stands, I'd expect your buffer to overrun, trashing memory as the loop runs and your application to crash.
After reflecting, I believe @FreeAsInBeer is correct and you don't want to iterate through the for loop in this situation and you could probably fix this by using signed ints. However, It seems to me like you would be better off, checking
len > sizeof(MSG_INFO)
and if this isn't the case handling it differently. Most situations I can think of, I wouldn't want to perform any processing after the for loop, if I'd failed to read sufficient information for a message...我不太确定这里发生了什么,因为循环不应该执行。我已经加载了您的代码,看来您的
int
声明中的unsigned
部分导致了问题。如果删除两个unsigned
说明符,您的代码将按预期执行,而无需进入循环。I'm not really sure what is going on here, as the loop should never execute. I've loaded up your code, and it seems that the
unsigned
part of yourint
declaration is causing the issues. If you remove both of yourunsigned
specifiers, your code will execute as it should, without ever entering the loop.