得到段错误的一个小C程序 [英] getting segmentation fault in a small c program

查看:99
本文介绍了得到段错误的一个小C程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小PROG:

  1#包括LT&;&stdio.h中GT;
  2主(){
  3字符*海峡=字符串;
  4 *海峡='K';
  5的printf(字符串=%S \\ n,STR);
  6}

这个程序被编译没有任何错误或警告,但是当我运行它,它给分段错误。而如果我重写3号线为:焦炭海峡[] =字符串;这个程序工作完全正常。任何人都可以请让我知道了什么​​是这里的问题?是什么写第三行的这两种不同方式之间的差异。任何帮助将大大AP preciated。谢谢。


解决方案

 的char *海峡=字符串;

声明指向哪里字符串存储的内存区域的指针;这是不确定的行为在这方面的记忆写的,它通常会导致崩溃。

相反,你应该使用:

 字符海峡[] =字符串;

该声明的字符串您的本地功能,即初始化为。由于使用该字符串的内存是本地到你的过程,你可以改变它不过你想要的。

i wrote a small prog :

  1 #include<stdio.h>  
  2 main(){  
  3         char* str = "string";  
  4         *str = 'k';  
  5         printf("string is = %s\n",str);
  6 }

This program gets compiled without any error or warnings, but when i run it, it gives segmentation fault. While if i rewrite the 3rd line as : char str[] = "string"; this program works perfectly fine. Can anyone please let me know what is the issue here ??? What is the difference between these two different ways of writing the 3rd line. Any help will be greatly appreciated. thanks.

解决方案

char * str = "string";

declares a pointer which points to an area of memory where the string "string" is stored; it's undefined behavior to write in this area of memory, and it usually results in a crash.

Instead, you should use:

char str[]="string";

which declares a string local to your function, that is initialized to the value "string". Since the memory you are using for this string is local to your procedure you can alter it however you want.

这篇关于得到段错误的一个小C程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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