-1

Is this is program to print prime numbers between two numbers a and b (null safe or not)?

if not , How to add null safe function to make it (NULL SAFE)

I have tried checking if argv[1] or argv[2] are equall to 0 but it is not how it should work

any Ideas for this?

//check if a or b or both are negative numbers
int check_negative(int *x, int *y){

    if(*x<0 || *y<0)
    {
        printf("Error : One or Both arguments are Negative\n");
        return 1;
    }
}

//check if n is a prime number
int isprime(int n)
{
    int i, status = 1;

    for(i=2; i <= n/2; ++i)
    {
        if (n%i == 0)
        {
            status = 0;
            break;
        }
    }
    return status;
}

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

    if(argc==1)
    {
        printf("Error : No arguments were passed\n");
        return 0 ;
    }

    int a=atoi(argv[1]),b=atoi(argv[2]),n,status;

    if(check_negative(&a,&b)==1)
    {
        return 0;
    }

    printf("Prime numbers between %d and %d are: \n", a, b);

    for(n=a+1; n<b; ++n)
    {
       status = isprime(n);

       if(status == 1)
           printf("%d  ",n);
    }
    return 0;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
Wesam
  • 1
  • 1

1 Answers1

1

Is this c program null safe?

No.


The below fails when argc < 3 (e.g. 2,1,0) as it calls atoi() with NULL or unknown. @Ian Abbott

int a=atoi(argv[1]),b=atoi(argv[2]),n,status;

Instead change prior test from only testing against 1 to the below. Note that argc == 0 is possible on select platforms and with certain function calls.

// if(argc==1)
if(argc < 3)

As a stand-alone function, check_negative() does not check if a null pointer argument is passed before de-referencing. Add checks

int check_negative(int *x, int *y){
  if (x == NULL || y == NULL) return 0;  /// or handle in some way

Aside:

isprime(Any_int_less_than_2) errantly returns 1.

for(i=2; i <= n/2; ++i) is very slow for large n. Suggest speedier for(i=2; i <= n/i; ++i). Sample

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256