简体   繁体   English

strtol在调试和发布模式上有所不同

[英]strtol differs in debug and release mode

I use following code in c++ compiling with visual studio 2008: 我在Visual Studio 2008的C ++编译中使用以下代码:

char input = 'K';
long output= strtol(&input , NULL, 36);

In debug mode it works fine, the output is 20. 在调试模式下,它可以正常工作,输出为20。
But in release mode it makes strange outputs, like 604663109. 但是在释放模式下,它会产生奇怪的输出,例如604663109。
It also works, when I set disable code optimization, but that can't be the solution. 当我设置禁用代码优化时,它也可以工作,但这不是解决方案。
I also know, how to calculate it by hand, but I want to know, why there is a difference between debug and release mode? 我也知道如何手工计算它,但是我想知道为什么调试和发布模式之间会有区别?

EDITED: Sorry, it has to be char and not char*. 编辑:抱歉,它必须是char而不是char *。 But same error. 但是同样的错误。

strtoul doesn't work on char, only on null terminated strings. strtoul对char无效,仅对以null结尾的字符串有效。 You'll have to use a null terminated string, or find another way. 您必须使用以null终止的字符串,或者寻找另一种方法。 Eg 例如

char input = 'K';
...
char temp[2] = { input, '\0' };
long output = strtol(temp, NULL, 36);

Since &input doesn't point to a null-terminated character array, the code has undefined behaviour. 由于&input并不指向以null结尾的字符数组,因此代码具有未定义的行为。

This should work: 这应该工作:

const char* input = "K";
long output = strtol(input , NULL, 36);

The reason it appears to work in the debug build is probably that the compiler has inserted "magic" values around the input variable in order to enable detection of stack corruption, and a zero happens to be placed at &input + 1 . 似乎在调试版本中起作用的原因可能是编译器已在input变量周围插入了“魔术”值,以便能够检测堆栈损坏,并且在&input + 1处放置了零。

Your call is wrong, you shouldn't take the address of the pointer! 您的通话错误,您不应该使用指针的地址!

It should be: 它应该是:

strtoul(input, NULL, 36);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM