[英]How to avoid stack overflow when passing an array to a function in C++?
我正在研究通過將指針傳遞到第一個位置將數組傳遞給函數的代碼。 在函數中,使用了數組的一部分。 這會造成不安全的情況,因為如果調用者函數沒有正確猜出數組的最大大小,則被調用者函數可能會寫入超出數組大小的位置,並且可能發生堆棧溢出。 我正在考慮解決此問題的方法,並考慮使用功能模板並將數組作為參考傳遞,如本示例所示。
modifyArray.h
#define MAXSIZE 10
class modifyArray
{
public:
void create();
void unsafeFunction(double*);
template<int N>
void safeFunction(double (&array)[N] );
private:
int computeLength();
};
modifyArray.cpp
#include <iostream>
#include "modifyArray.h"
int modifyArray::computeLength()
{
return 11;
}
void modifyArray::create()
{
double testarray[MAXSIZE];
unsafeFunction(testarray);
safeFunction(testarray);
}
void modifyArray::unsafeFunction(double* array)
{
int operatingSize = computeLength();
for(int i = 0; i < operatingSize; i++) {
array[i] = i*i;
}
}
template<int N>
void modifyArray::safeFunction(double (&array)[N] )
{
int operatingSize = computeLength();
std::cout<< "Max size" << N <<std::endl;
if(operatingSize > N) return; // Return or raise an exception
for(int i = 0; i < operatingSize; i++) {
array[i] = i*i;
}
}
main.cpp中
#include "modifyArray.h"
int main(int argc, const char * argv[]) {
modifyArray C;
C.create();
return 0;
}
我正在尋找一種對現有代碼的影響最小的解決方案。 在這里,我只需要添加一個模板語句,將參數從double *更改為reference,然后插入if語句來檢查大小。 我不想進行重大重寫。 我也不想使用動態分配,向量或std :: array主要是因為性能原因。 這是數字仿真代碼中的低級函數,性能非常重要。 有更好的解決方案嗎? 做我的工作有陷阱嗎?
如果您真的想使用原始數組,並且想要安全地修改數組的所有元素而不必走到最后,則可以按引用傳遞數組,然后使用基於范圍的for循環 。
tmeplate <typename T, typename Function, std::size_t N>
void do_work(T (&arr)[N], Function f)
{
for (auto & e : arr)
e = f();
}
上面將調用函數的結果應用於數組的每個元素,並保證將其保留在數組的邊界內。 你可以像這樣使用它
int main()
{
int arr[10];
do_work(arr, []() { static int i = 0; i++; return i * i; });
for (auto e : arr)
std::cout << e << " ";
}
輸出:
1 4 9 16 25 36 49 64 81 100
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.