C++ 函数中返回字符串的一个陷阱

 1 #include<iostream>
 2 using namespace std;
 3 char * getname(void);
 4 int main()
 5 {
 6     char * name;
 7     name = getname();
 8     cout << "My name is : " << name << endl;
 9     cout << "---------华丽的分割线----------" << endl;
10     return 0;
11 }
12 char * getname()
13 {
14     char get_name[30];
15     cout << "Enter your name :";// a word
16     cin >> get_name;
17     return get_name;
18 }

可能第一眼看上去没什么毛病,BUT  getname()里面的get_name是一个字符串数组。在函数return之后这个get_name会释放内存(因为她在栈中,函数执行玩会弹栈)。所以main函数中的name变成了一个野指针,这是一个很危险的操作。

解决办法:返回一个在堆中的地址。

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 char * getname(void);
 5 int main()
 6 {
 7     char * name;
 8     name = getname();
 9     cout << "My name is : " << name << endl;
10     cout << "---------华丽的分割线----------" << endl;
11     return 0;
12 }
13 char * getname()
14 {
15     char get_name[30];
16     cout << "Enter your name :";// a word
17     cin >> get_name;
18     char * name = new char[strlen(get_name)+1];
19     strcpy(name, get_name);// do not use name = get_name
20     //because name will get get_name address it‘s in the stack
21     //it is stupid idea.
22     return name;
23 }

考虑到内存的问题记得要在new之后不用了要delete,释放内存资源。

delete [] name;

没学过C语言,照着文档用malloc-free版本的。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdlib>
 4 using namespace std;
 5 char * getname(void);
 6 int main()
 7 {
 8     char * name;
 9     name = getname();
10     cout << "My name is : " << name << endl;
11 //    delete [] name;
12     free(name);
13     cout << "---------华丽的分割线----------" << endl;
14     return 0;
15 }
16
17 char * getname()
18 {
19     char get_name[30];
20     cout << "Enter your name :";// read a word
21     cin >> get_name;
22     char * name = (char*)malloc(strlen(get_name)+1);
23     strcpy(name, get_name);
24     return name;
25 }

附上文档:

free了不代表这个指针不能用了,只是释放了内存地址。

时间: 2024-07-31 19:50:45

C++ 函数中返回字符串的一个陷阱的相关文章

C语言strstr()函数:返回字符串中首次出现子串的地址

今天又学到了一个函数 头文件:#include <string.h> strstr()函数用来检索子串在字符串中首次出现的位置,其原型为:    char *strstr( char *str, char * substr ); [参数说明]str为要检索的字符串,substr为要检索的子串. [返回值]返回字符串str中第一次出现子串substr的地址:如果没有检索到子串,则返回NULL. [函数示例]strstr()函数的使用. #include<stdio.h> #inclu

关于在函数中返回动态的内存

1.有以下题目: 1 #include <iostream> 2 using namespace std; 3 4 void GetMemeory(char* p) 5 { 6 p=(char*)malloc(sizeof(char)*100); 7 } 8 9 int main() 10 { 11 char *str=NULL; 12 GetMemeory(str); 13 strcpy(str,"Thunder"); 14 strcat(str,"Downlo

用python从字符列表中返回字符串字符的位置

需要从字符列表中找出每个字符在字符串中的位置,然后将整个字符位置返回到单个字符串中,每个字符位置之间的空格除外最后一个.您需要忽略所有不在字符列表中的由az中的字符组成的字符. 策略: 首先,我们需要在列表中声明az字符的列表. alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',

C语言strlen()函数:返回字符串的长度

头文件:#include <string.h> strlen()函数用来计算字符串的长度,其原型为:    unsigned int strlen (char *s); [参数说明]s为指定的字符串. strlen()用来计算指定的字符串s 的长度,不包括结束字符"\0". [返回值]返回字符串s 的字符数. 注意一下字符数组,例如    char str[100] = "http://see.xidian.edu.cn/cpp/u/biaozhunku/&quo

Swift中返回字符串的宽度

最近在用swift 开发软件,但是iOS8要求更加严格,以前获取字符串的宽度的方法,都不能用,自己写了个,虽然很简单,但是希望和大家分享. <span style="font-size:18px;"> // MARK:返回字符串的宽度 func returnWidth(string:NSString) -> CGFloat { let size: CGSize = string.sizeWithAttributes([NSFontAttributeName: UIFo

C语言中返回字符串函数的四种实现方法

有四种方式: 1.使用堆空间,返回申请的堆地址,注意释放 2.函数参数传递指针,返回该指针 3.返回函数内定义的静态变量(共享) 4.返回全局变量 其实就是要返回一个有效的指针,尾部变量退出后就无效了. 使用分配的内存,地址是有效 char   *fun() {         char*   s   =   (char*)calloc(100,   sizeof(char*)   );         if   (s)                 strcpy   (   s   ,  

JS 函数中返回另一个函数

function createComparisonFunction(propertyName) { return function (object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return

编写一个函数,由实参传来一个字符串,统计此字符串中字母,数字,空格,和其他字符的个数,在主函数中输入字符串以及输出上述统计的结果。再考虑将算的的结果放在一个数组中

#include<stdio.h> #include<string.h> int f(int g,char s[],int h[]) { int i,a=0,b=0,c=0,d=0; for(i=0;i<g;i++) { if(s[i]>='a'&&s[i]<='z') h[0]++; else if(s[i]>='0'&&s[i]<='9') h[1]++; else if(s[i]==' ') h[2]++; els

PHP程序中删除字符串最后一个字符的三种方法

常见的语法格式: foreach ($arr as $key => $value) {$arr_str = $arr['x_id'] . ',' . $arr_str;} 假设字符数组 $arr 中的字符分别为 arr[0] = 'a';arr[1] = 'b';arr[2] = 'c'; 则,拼接后的 $arr_str 字符串为 a,b,c, 这个时候,就需要我们对最后一位字符','进行删除处理. 二php中删除最后一位字符的方法总结: 方法一: substr($arr_str,0,strle