【问题标题】:Armstrong Numbers Bufferoverflow阿姆斯壮数字缓冲区溢出
【发布时间】:2012-11-06 15:07:27
【问题描述】:

目前我正在尝试构建一个程序来打印所有 armstrongnumbers 直到某个数字。尝试运行此程序时出现一些奇怪的错误。它说缓冲区溢出。 导致它的部分似乎在 main() 中。感谢您的帮助。

#include <stdio.h>
#define MAXIMUM 1000000

int ipow(int x, int power){ 
int z,t;
t = 0;
z = x;
for (t = 0; t < (power - 1); t++) {
    z = z * x; }
return z;
}


int getLength(int x) { 
    int a;
    a = 1;
    for (a=1;1;a++) { if (x < ipow(10,a) && x >= ipow(10,(a-1))) return a; }
}

int getExpSum(int x) { 
    int summe,r,s,t;
    int digit[8]={0,0,0,0,0,0,0,0};
    summe=0;
    s = getLength(x);
    t = x;
    r = 1;
    for (s=getLength(x);s!=0;s--){
        digit[s] = t % 10;
        t = t / 10;
    }
    for(r=1;r<(getLength(x)+1);r++)
    {
        summe = summe + ipow(digit[r],getLength(x));
    }
    return summe;
}

int Armstrong (int x) {
    if (getExpSum(x)==x) {
        printf("%d ist eine Armstrongzahl\n", x);
        return 1;
    }
    return 0;
}

void main(){
    int z;
    z = 0;
    for (z=0;z<MAXIMUM;z++){
        Armstrong(z+1);
    }
}

【问题讨论】:

  • for (a=1;a=a;a++) 棘手且没有任何好处。
  • @user1803470:for (a = 1; ; ++a)。或者for (a = 1; 1; ++a),如果您不喜欢空条件的外观,但有些编译器会为此发出警告。
  • 已将其更改为 1。谢谢。主要错误仍然存​​在。

标签: c buffer-overflow


【解决方案1】:

你的“getLength”函数有问题(实际上是ipow)

通过 getLength(1) 你得到的结果是 13 因为 ipow(10, 1) 和 ipow(10, 0) 返回 10,因此“getLength”条件失败,它会进行下一次迭代并继续......直到 ipow 由于整数大小而返回一个负数,即 10^13。

在 getExpSum 中,数组数字的大小为 8,它尝试访问它的第 13 个元素。因此它崩溃了

在ipow函数中添加条件

int ipow(int x, int power){ 
int z,t;
t = 0;
z = x;
 if (power == 0) //<-----add this condition to your code
     return 1;

for (t = 0; t < (power - 1); t++) {
    z = z * x; }
return z;
}

添加此条件后,我得到了正确的结果。

1 ist eine Armstrongzahl
2 ist eine Armstrongzahl
3 ist eine Armstrongzahl
4 ist eine Armstrongzahl
5 ist eine Armstrongzahl
6 ist eine Armstrongzahl
7 ist eine Armstrongzahl
8 ist eine Armstrongzahl
9 ist eine Armstrongzahl
153 ist eine Armstrongzahl
370 ist eine Armstrongzahl
371 ist eine Armstrongzahl
407 ist eine Armstrongzahl
1634 ist eine Armstrongzahl
8208 ist eine Armstrongzahl
9474 ist eine Armstrongzahl
54748 ist eine Armstrongzahl
92727 ist eine Armstrongzahl
93084 ist eine Armstrongzahl
548834 ist eine Armstrongzahl

顺便说一句,解决方案可以改进。

【讨论】:

  • 是的,它可能可以做到。但是我不久前才开始学习 C,因此如果我得到一个可行的解决方案,我会很高兴。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 2021-04-03
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 2011-08-07
相关资源
最近更新 更多