gpt4 book ai didi

c++ - 如何解决 C++ 中的这个运行时错误? - "Stack around variable was corrupted"

转载 作者:行者123 更新时间:2023-12-02 18:13:45 27 4
gpt4 key购买 nike

我尝试获取 two integers最小值 , real numbers , strings ,和integer arrays通过实现与函数重载获得类似处理结果的函数。

所以我写这样的代码

#include <iostream>  
#include <cstring>
using namespace std;

int GetMin(int a, int b);
double GetMin(double a, double b);
char* GetMin(char* a, char* b);
int GetMin(int* arr, int size);


int main()
{
int num1, num2;
double num3, num4;
char s1[30], s2[30];
int arr[10];

cout << "Enter two integers : ";
cin >> num1 >> num2;
cout << "The minimum value is " << GetMin(num1, num2) <<"\n";

cout << "Enter two real numbers : ";
cin >> num3 >> num4;
cout << "The minimum value is " << GetMin(num3, num4) <<"\n";

cout << "Enter two strings : ";
cin >> s1 >> s2;
cout << "The minimum value is " << GetMin(s1,s2) <<"\n";

cout << "Elements of an Array : ";
cin >> arr[10];
cout << "The minimum value is " << GetMin(arr[10], 10);


}


int GetMin(int a, int b)
{
if (a > b) return b;
else return a;


}


double GetMin(double a, double b)
{
if (a > b) return b;
else return a;

}


char* GetMin(char* a, char* b)
{
if (strcmp(a, b) < 0) return a;

}


int GetMin(int* arr, int size)
{
int min = arr[0];
for (int i = 1; i<size; i++)
if (arr[i] < min)
min = arr[i];
return min;

}

这是所需的结果。

Enter two integers : 10 20 
The minimum value is 10
Enter two real numbers : 56.84 120.26
The minimum value is 56.84
Enter two strings : orange apple
The minimum value is apple
Elements of an Array : 41 67 34 25 0 54 98 21 58 62
The minimum value is 0

我收到此错误消息。

Run-Time Check Failure #2 - Stack around the variable 'arr' was corrupted.

最佳答案

使用cin给整个数组赋值是错误的。更常见的方法是使用 forwhile 结构。我建议您阅读此issue了解输入和输出。

此外,您是否在程序中观察到警告?

enter image description here

Warning C6201 Index '10' is out of valid index range '0' to '9' forpossibly stack allocated buffer 'arr'.

数组arr[10]的索引应该是arr[0]~arr[9]。关于C6385,您应该阅读此document .

char* GetMin(char* a, char* b)
{
if (strcmp(a, b) < 0) return a;

}

最好不要使用函数的参数作为返回值。常见的方法是定义一个变量来存储要返回的参数。

关于c++ - 如何解决 C++ 中的这个运行时错误? - "Stack around variable was corrupted",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71920324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com