为什么使用在C格式错误说明崩溃我的程序在Windows 7? [英] Why does using the wrong format specifier in C crash my program on Windows 7?

查看:253
本文介绍了为什么使用在C格式错误说明崩溃我的程序在Windows 7?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序如下;

#include <stdio.h>
#include <string.h>

int main()
{
        char string[] = "Gentlemen start your engines!";
        printf("That string is %s characters long.\r\n", strlen(string));
        return 0;
}

我在编译GCC,虽然它并没有给我任何错误的程序崩溃每次我运行它。在code似乎是从我所看到的例子罚款。这将会是伟大的知道,如果我做错什么。

I'm compiling under gcc, and although it doesn't give me any errors the program crashes every time I run it. The code seems to be fine from examples I've seen. It'd be great to know if I'm doing anything wrong.

感谢。

推荐答案

使用不正确的格式说明符的printf()调用未定义行为。正确的格式说明应%祖(不是%d个),因为返回类型的strlen ()为size_t

Using incorrect format specifier in printf() invokes Undefined Behaviour. Correct format specifier should be %zu (not %d) because the return type of strlen() is size_t

请注意:长度修改以Z %祖重新presents长度相同的整数为size_t

Note: Length modifier z in %zu represents an integer of length same as size_t

这篇关于为什么使用在C格式错误说明崩溃我的程序在Windows 7?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆