0

I executed the below C program which prints a the primes below the given N (N < 4294967295). It went fine when executed in SunOS, but I'm getting Segmentation fault (core dumped) when running in Ubuntu(compiled it with gcc compilter). Can anyone please let me know where I went wrong. Mentioned below the compiler versions of SunOS and Ubuntu 12.10

cc -V

cc: Sun C 5.9 SunOS_sparc Patch 124867-01 2007/07/12

gcc -v

Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.7/lto-wrapper Target: x86_64-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.7.2-2ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --enable-objc-gc --disable-werror --with-arch-32=i686 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu Thread model: posix gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<inttypes.h>

int main()
{
FILE *fpin,*fpout;
char ch[11], file_name[100];
long long int num1=0,i,tmp=0;
long long int *arr;

printf("enter file name:: ");
gets(file_name);

fpin = fopen(file_name,"r");
fpout = fopen("/home/code/output.c","w");

while(1)
{
 fgets(ch,11,fpin);
 if (!feof(fpin))
 {
   num1=atoll(ch);

   arr = prime_number(num1);

   for(i=0;*(arr+i)!='\0';i++)
      {
         fprintf(fpout,"%llu",*(arr+i));
         if(*(arr+i+1) == '\0')
             fputc('.',fpout);
         else
             fputc(',',fpout);
      }

 }
 else 
 {
   fclose(fpin);
   fclose(fpout);
   break;
 }
}

}

prime_number(long long int n)
{
  long long int i,j,total=0,a[200];
  int count=0;

  printf("\n%llu \n",n);

  for (j=2;j<=n;j++)
  {
     count = 0;
     for (i=1;i<=j;i++)
       {`enter code here`
         if ((j%i) == 0)
           count++;

         if (count > 2)
            break;
        }
     if (count==2)
        {
          a[total] = j; 
          total++; 
        }
  } 
return(&a[0]);
}
4

2 回答 2

2

在 prime_number 函数结束时,您将返回一个指向在 prime_number 函数本身(堆栈)中定义的变量的指针。因为当函数存在时,它的堆栈内容被有效地蒸发了,所以你返回了一个无效的指针。

当然,根据您正在运行的系统、操作系统等,堆栈的内容可能没有被立即覆盖,并且会在短时间内有效,但这只是运气。

尝试分配返回结果(并与调用者一起释放),或将数组传递给 prime_number 函数。这样,内容将对调用者保持有效。

于 2013-04-01T16:53:22.997 回答
1
return(&a[0]);

您正在返回一个指向局部变量的指针,该变量在您的函数返回后不存在。

如果您运行 gcc 时出现警告,您的编译器应该会告诉您这一点。

于 2013-04-01T16:51:42.840 回答