您的位置:首页 > 其它

一道关于内存操作和strcpy的笔试题

2013-04-21 23:42 148 查看
/**
char* strcpy(char* _Dest, const char* _Source);
不管strlen(_Dest)和strlen(_Source)的大小关系如何,strcpy总能成功执行,并且执行完copy之后,会在内容的后面补上'\0'。
*/

#include <iostream>
using namespace std;

void GetMomery1(char** str, int a)
{
*str = (char*)malloc(sizeof(a));
}

char* GetMomery2()
{
char* str = new char[8];
strcpy(str, "HelloWorld2!");
return str;
}

char* GetMomery3()
{
char str[16] = "HelloWorld3!";
return str;
}

int main(int argc, char* argv[])
{
char* str1;
GetMomery1(&str1, 100);
strcpy(str1, "HelloWorld1!");
printf("%s\n", str1);

char* str2 = GetMomery2();
printf("%s\n", str2);

char* str3 = GetMomery3();
printf("%s\n", str3);

char* str4 = (char*)malloc(128);
strcpy(str4, "HelloWorld4!");
//free(str4);
if(str4 != NULL)
{
strcpy(str4, "HelloWorld4!"); //如果上面去掉注释,执行了“free(str4);”,则这里会有runtime error
printf("%s\n", str4);
}

system("pause");
return 0;
}

/*
Output:

HelloWorld1!
HelloWorld2!
?
HelloWorld4!
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: