[英]Is shifting std::bitset<N> more than N positions undefined behavior?
[英]Using more elements in array than allocated has undefined behavior
我有三角形的結構,用戶必須輸入他想擁有的三角形的數量,然后為每個-邊長填充數據。 然后程序寫入最大長度的邊。 首先,我為三角形數組分配內存,然后用數據填充每個三角形,但是我的程序從未將最后輸入的三角形保存在數組中,並且得到了一些奇怪的數字作為最大邊。 這是我的代碼
struct triangle
{
int a;
int b;
int c;
};
int getBiggestEdge(int a, int b, int c)
{
int max = a;
if(b>max) {max=b;}
if(c>max) {max=c;}
return max;
}
int maxEdge(struct triangle niz [], int br)
{
int i, najduza;
najduza = getBiggestEdge(niz[0].a, niz[0].b, niz[0].c);
for(i=1; i<=br; i++)
{
if(getBiggestEdge(niz[i].a, niz[i].b, niz[i].c) > najduza)
{
najduza = getBiggestEdge(niz[i].a, niz[i].b, niz[i].c);
}
}
return najduza;
}
int main()
{
int i, n, edge;
struct triangle* niz;
printf("Insert number of triangles: ");
scanf("%d", &n);
niz= (struct triangle*) malloc(n * sizeof(struct triangle));
if (niz == NULL)
{
printf("Error!");
return 0;
}
printf("Insert data for every triangle (a b c):\n");
for(i=0;i<n;i++)
{
printf("Triangle: ");
scanf("%d %d %d", &niz[i].a, &niz[i].b, &niz[i].c);
}
edge = maxEdge(niz, n);
printf("Biggest edge is: %d\n",edge);
free(niz);
return 0;
}
您在maxEdge
中使用了錯誤的索引:
for(i=1; i<=br; i++)
它應該是
for(i = 0; i < br; i++)
在主循環中,您可以使用它來糾正錯誤,但是在函數中,您正在讀取數組邊界之外的內容並獲取未定義的數據。
無關但值得一提的是,您不應該轉換malloc
返回的指針:
您正在使用malloc(n * sizeof(struct triangle))
為n個數組元素分配空間,並通過以下方式為n個元素獲取輸入:
for(i=0;i<n;i++)
但是使用以下方法訪問n + 1個元素:
for(i=1; i<=br; i++)
在maxEdge
。 此處br
的值為n
,因此代碼訪問n + 1個元素(索引從0到n),該元素具有未定義的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.