主要数目N的分段错误(N> 10000)

时间:2015-07-12 07:35:34

标签: c

我在我的程序中遇到了一个分段错误,寻找的素数达到N.

我使用素数的动态链表来测试N的效率。

问题是当N <= 17508时它起作用。它失败了更大的N.特别是当我把打印输出加起来时,它总是有分段错误。有人可以帮忙吗?感谢。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct prime{
long value;
struct prime *next;
}prime;

long numofprime(long n)
{
long a, b, c;

prime *head, *p1, *p2, *p3;
int flag;

if(n<0)
n=-n;

if(n<2)
    return 0;
else if(n==2)
    return 1;
else
{/*creat linked list*/
   p1=(prime *)malloc(sizeof(prime));
   p1->value=2;
   p1->next=NULL;
   p2=p1;
   head=p1;

        b=1;
        for(a=3;a<=n;a+=2)
        {
            flag=0;
            p3=head;
            while(p3!=NULL)
            {
                c=p3->value;
                if(a%c==0)
                {
                    flag=1;
                    break;
                }
                p3=p3->next;
            }

            if(flag==0)
            {/*add prime number to the linked list*/
                p1=(prime *)malloc(sizeof(prime));
                p1->value=a;
                p2->next=p1;
                p2=p1;
                b++;
            }
        }

        c=0;
        while(head!=NULL)
        {
            printf("%5ld ", head->value);
            if(c%15==0) printf("\n");
            head=head->next;
            c++;
        }

        return b;
    }

}

int main(int argc, char *argv[])
{

long n;
long np;

if(argc<2)
{
    printf("Please input the max num!\n");
    exit(0);
}
else if(argc>2)
{
    printf("Too many arguments!\n");
    exit(0);
}
else
    n=strtol(argv[1], NULL, 10);

    np=numofprime(n);

    printf("\n\nthere are %ld primes < n!\n", np);

    return 0;
 }

1 个答案:

答案 0 :(得分:3)

在为链接列表分配新项目时,始终将指向next项目的指针设置为NULL。否则,无法检测到链表的末尾,出现未定义的行为,并且可能出现分段错误。

例如:

        {/*add prime number to the linked list*/
            p1=malloc(sizeof(prime));
            if(p1==NULL){fprintf(stderr,"failed to allocate\n");exit(1);}
            p1->value=a;
            p1->next=NULL; ///this new line here
            p2->next=p1;
            p2=p1;
            b++;
        }

此外,不要忘记free()函数末尾的内存。执行head=head->next打印链接列表不会简化此操作,因为无法返回:指向链接列表开头的指针将丢失。始终在某处保留指向链接列表开头的指针!

相关问题