字符串常量修改问题

来源:互联网 发布:sql语句添加多个字段 编辑:程序博客网 时间:2024/04/29 13:39

  最近在写操作系统,遇到了不少问题......谁叫我只有薄弱的c++基础和java基础呢。在正式开始写内核之前还要先了解makefile,链接器脚本,grub,gcc......这些东西之前闻所未闻,光了解这些东西都花了我两周时间(当然,这两周也在干其他事,分配给操作系统的时间不多)。不过万事开头难,既然决定要写,总得熬过最开始的艰难期。这周(开学第三周),我终于开始了内核之旅。

  我是照着hurley的教程“一个基于x86架构的简单内核实现”来的。进入内核之旅后,第一步要做的就是写几个字符串操作函数。写函数strcat的过程中我遇到了一个问题:

代码是这样的:

char *strcat(char *dest,const char *src){char *dst = dest;while (*(++dst)!='\0'){}while((*(dst++) = *(src++))!='\0'){}return dest;}


int main(){char *c1="comma";char *c2=  "heihei";strcat(c1,c2);printf("%s",c1);}

用gdb进行调试,得到dest和src的初始地址分别是0x4008c4 和 0x4008ca。也就是说,它们是连续分配的。然而调试了半天,我还是不知道错在哪。


最后决定求助于搜索引擎,一番查找之后,得到的答案是:

On the other hand, the declaration
char *p = "abc";
defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array ofchar’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep to modify the contents of the array, the behavior isundefined.
修改字符串常量的行为是未定义的。我这里对常量进行操作,显然是不妥的。看了一些文章,有人说在不同编译器下会得到不同结果,有的会出错,有的不会。无论如何,修改字符串常量的事是不要再干了。





0 0
原创粉丝点击