段错误而deferencing字符数组 [英] Segmentation Fault while deferencing a char array

查看:159
本文介绍了段错误而deferencing字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #包括LT&;&stdio.h中GT;
INT主要(无效)
{
    的char * p =字符串是好的;
    的printf(%S,* P);
    返回0;
}

可能有人请告诉我为什么我在这里得到段错误?


解决方案

  

可能有人请告诉我为什么我在这里得到段错误?


C11:7.21.6格式化输入/输出功能:


  

如果一个转换说明是无效的,行为是undefined.282)如果任何参数类型不正确的相应转换规范,行为
  未定义。


3.4.3


  

1 未定义行为
  行为,或者在错误数据的使用不可移植的或错误的程序构造,
  对于这本国际标准并没有规定要求。


  
  

2 注意可能的不确定的行为从与联合国predictable结果完全无视的情况下,在环境的记录方式的特点翻译或程序执行过程中的行为(有或没有发放范围诊断消息的),以终止翻译或执行(并出具诊断消息)。


* P 的类型为字符%S 预计键入的char * 的参数。这将调用的未定义行为即可。在这种情况下,什么事情都可能发生。有时你可能会得到预期的结果,有时不是。这也可能会导致程序崩溃或段错误(这是这里的情况)。

有关%S ,你需要传递的刺痛/文字的起始地址。

修改

 的printf(%S,* P);

 的printf(%S,P);

#include<stdio.h>
int main(void)
{
    char * p= "strings are good";
    printf("%s",*p);
    return 0;
}

Could somebody please tell me why I am getting segmentation fault here?

解决方案

Could somebody please tell me why I am getting segmentation fault here?

C11: 7.21.6 Formatted input/output functions:

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

3.4.3

1 undefined behavior behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.

2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

*p is of type char. %s expects argument of type char *. This will invoke undefined behavior. In this case anything could happen. Sometimes you may get the expected result and sometimes not. This may also cause program crash or segmentation fault (which is the case here).

For %s, you need to pass the starting address of the sting/literal.

Change

printf("%s",*p);  

to

printf("%s",p);

这篇关于段错误而deferencing字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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