strcat函数的坑点
我们先看下面这样一段代码:
#include <iostream>
#include <stdlib.h>
using namespace std; int main()
{
char *p1= "";
char *p2= "ABC";
char str[]= "xyz";
strcat(p1,p2);
strcpy(str+,p1);
cout<<str<<endl;
system("pause");
return ;
}
咋一看,这段代码的原意是将p2链接到p1的后面,p1为123ABC
然后将str字符数组向后移动两个位置,将p1拷贝到从该位置开始之后的内存中。
结果为xy123ABC
然而我们运行一下这段代码发现程序崩溃了,我们调用堆栈发现函数定位在这一行

咦,这是怎么回事
赶紧再查查strcat函数的用法,发现当链接p1和p2字符串的时候,将链接的字符串一起
存入p1中,那么就隐含了这么个意思,就是说P1的大小必须要容得下链接后的字符串。
但是本质上是字符串"123"是保存在程序中的常量区,而常量区只能进行读操作不能进行写
操作
那么我们在栈区定义一个较大的数组来保存连接后的结果。
char p1[]="";
现在我们再运行下看看结果:

这下果然正确了
strcat函数的坑点的更多相关文章
- C语言strcat()函数:连接字符串
头文件:#include <string.h> strcat() 函数用来连接字符串,其原型为: char *strcat(char *dest, const char *src); ...
- strcat函数的使用需要注意的问题
曾被这个函数困扰了好久,然后各种假设,验证:但是最后却发现这个函数并没有什么好讲的,原来的过错一切都源于忽略了“*dst去掉\0,然后加上*src,最后返回*dst”这句话的真正含义:给*dst分配的 ...
- strcat()函数常见问题
strcat(char *_Destination,const char *_Source)函数的功能是将后一个字符串粘贴到前一个字符串的末尾 原型 char *strcat(char *_Desti ...
- strcat函数造成的段错误(Segmentation fault)
转自:http://book.51cto.com/art/201311/419441.htm 3.21 strcat函数造成的段错误 代码示例 int main() { char dest[7]=& ...
- 【C语言】模拟实现库函数strcat函数
//模拟实现库函数strcat函数 #include <stdio.h> #include <string.h> #include <assert.h> char ...
- 编写一个程序实现strcat函数的功能
写自己的strcat函数------→mycat #include <stdio.h> #include <string.h> #define N 5 char *mycat( ...
- C语言中strcpy,strcmp,strlen,strcat函数原型
//strcat(dest,src)把src所指字符串添加到dest结尾处(覆盖dest结尾处的'\0')并添加'\0' char *strcat(char * strDest, const char ...
- 由strcat函数引发的C语言中数组和指针问题的思考
问题一 首先,来看一下下面这段代码: #include <stdio.h> #include <string.h> int main() { char *str = " ...
- strlen函数,strcat函数,strcpy函数,strncpy函数,strcmp函数
strcpy函数: char *strcpy(char *Dest , const char *Src) { assert((Dest != NULL) && (Src != NULL ...
随机推荐
- windows服务程序
首先创建一个myService的窗体程序作为服务安装卸载控制器(管理员身份运行vs,windows服务的安装卸载需要管理员权限) 在同一个解决方案里面添加一个windows服务程序,取名myWin ...
- 【小程序开发】微信小程序开发中遇到的那些坑...
第一坑: 设置了三个tabBar,却默认显示第二个,不能展示我的第一个[首页]. "list": [{ "pagePath":"page/KTGJ/i ...
- javascript实现限制上传文件的大小
目录 基本思路 示例 [一].基本思路 在FireFox.Chrome浏览器中可以根据document.getElementById(“id_file”).files[0].size 获取上传文件的大 ...
- [React] Extracting Private React Components
we leverage private components to break our render function into more manageable pieces without leak ...
- [Falcor] Return the data from server
<!-- index.html --> <html> <head> <!-- Do _not_ rely on this URL in production. ...
- C++ Win32控制台应用程序捕捉关闭事件
#include#includebool ctrlhandler( DWORD fdwctrltype ){ switch( fdwctrltype ) { // handle ...
- error C2143: 语法错误 : 缺少“;”(在“using”的前面)
class JJMenuScene : public cocos2d::CCLayer { public: // Here's a difference. Method 'init' in cocos ...
- 一年后重翻javascript
回想下自己的工作历程 一年多的ios开发眨眼间就过去了 不过这一切还没有结束,紧随其后的便是前段开发,虽然顶点基础都没有,但是还是通过我的不懈努力最终成功转型,虽然刚开始是通过jq直接入门的 ...
- django: db - many to many
本讲介绍数据库多对多关系,代码样例继前文使用. 一,在 blog/models.py 中创建对象: # Many-To-Many Example : Authors vs Books class Au ...
- css变形几大属性
1.transform: transform-function() * | none; transform-function: translate().scale().rotate().skew(). ...