求C++大佬看看,我的输出结果为什么是这样的?

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
class Point {

public:

    float x,y;

};
class Polygon
{
private:
	int nLength;
	Point *Vertex;
public:
	Polygon(int n)
	{
		nLength=n;
	}
	void Set(int idx,Point pnt)
	{
		Vertex=(Point*)malloc(sizeof(Point)*nLength);
		int t=idx;
		Vertex[t]=pnt;
	}
	float Perimeter()
	{
		float cau=0;
		int h=0;
		for(h=0;h<nLength;h++)
		{
			cau=cau+sqrt(pow((Vertex[h].x-Vertex[h+1].x),2)+pow((Vertex[h].y-Vertex[h+1].y),2));
		}
		cau=cau+sqrt(pow((Vertex[0].x-Vertex[nLength-1].x),2)+pow((Vertex[0].y-Vertex[nLength-1].y),2));
		return cau;
	}
};
int main()
{
	int n =0;

   Point pnt;

   cin >> n;

   Polygon po(n);

   for(int i=0;i<n;i++)

   {

       cin >> pnt.x >>pnt.y;

       po.Set(i, pnt);

   }

   printf("%4.1f", po.Perimeter());

   return 1;
}

 

在 Polygon 类的构造函数中,虽然已经传入了多边形的边数 n,但并没有在构造函数中为 Vertex 数组分配内存空间,而是在 Set 函数中动态分配内存,这样会导致内存泄漏,因为每次调用 Set 函数都会重新分配一次内存,但之前分配的内存没有被释放。

在 Perimeter 函数中,由于循环变量 h 的范围是 0 到 nLength-1,所以在计算最后一个点到第一个点的距离时,会访问到 Vertex[nLength],这样会导致访问越界的问题。