为什么没有捕获返回值时没有错误
Why is there no error when the return value is not catched?
据我所知,从返回类型函数接收到的值必须存储在调用它的位置,否则就会出错。请解释下面的代码是如何正常工作的。
#include <iostream>
#include <stdlib.h>
#include<assert.h>
//Returns a pointer to the heap memory location which stores the duplicate string
char* StringCopy(char* string)
{
long length=strlen(string) +1;
char *newString;
newString=(char*)malloc(sizeof(char)*length);
assert(newString!=NULL);
strcpy(newString,string);
return(newString);
}
int main(int argc, const char * argv[])
{
char name[30]="Kunal Shrivastava";
StringCopy(name); /* There is no error even when there is no pointer which
stores the returned pointer value from the function
StringCopy */
return 0;
}
我在Xcode中使用c++。
谢谢。
在C++中不需要使用函数调用(或任何其他表达式)的结果。
如果您想避免由于返回一个指向动态内存的哑指针并希望调用方记得释放它而可能导致的内存泄漏,那么不要这样做。返回一个RAII类型,它将自动为您清理任何动态资源。在这种情况下,std::string
将是理想的;甚至不需要编写函数,因为它有一个合适的构造函数。
一般来说,如果你在写C++,就不要写C。
相关文章:
- 方法错误"not all control paths return a value"和方法不返回值
- __int64 CString 返回错误的值 - C++ MFC
- 函数从指针 c++ 中获取错误的值并返回错误的答案
- 不断收到错误消息,并非所有控制路径都返回值
- 除法函数返回错误的值
- CUDA返回值错误35的含义是什么
- 是否有一些东西限制了未来引入多个返回值C++标准?
- 为什么时间测量有时会返回重复值(15.625ms 的倍数)?
- 不从函数返回值会导致段错误
- C++ std::tm 从 std::chrono::time_point 转换后返回错误的值
- 标准库to_string(双精度)在 vs2015 中给出错误的值.有什么解决办法吗?
- 如果函数的返回值将用作右值引用而不是左值,有没有办法使函数具有不同的行为?
- 返回值是否会有临时被销毁?
- 动态指针引用数组由三元运算符返回值,但有异常
- 为什么 GCC 无法优化,除非返回值有名称?
- C++ ExpandEnvironmentStringsForUser 函数有时会返回错误的值
- 对于大于 4GiB 的文件,fread 有时会返回错误的值
- 存储在静态常量整数 (C++) 中的对数函数的错误返回值
- 为什么这个“int”有错误的值
- 是否有可能避免有关 void 函数返回值的外部引用换行错误