Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does this keep printing "out of range try again"? and how can i fix it

For some reason this will print out "out of range please try again". I tried changing the if statements but that doesn’t work either.

#define MAX_fn_LEN32
#define MAX_ln_LEN32
#define MAX_stA_LEN64
#define MAX_city_LEN32
#define MAX_state_LEN32
#define MAX_buffer_LEN32
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
int main(){

char* fn=NULL;
bool a=false;

fn = malloc(32 * sizeof(char));;

printf("what is your first name?\n");
scanf("%s",fn);

while(a==false){

  if(fn==NULL ||fn>=(32*sizeof(char))){

    printf("Out of range try again.\n");
    scanf("%s",fn);
    a=false;
  }
  else{

    printf("This works.\n");
    a = true;
    return 0;
}

}
  free(fn);

}

For some reason this will print out "out of range please try again". I tried changing the if statements but that doesn’t work either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The condition in the if statement

if(fn==NULL ||fn>=(32*sizeof(char))){

does not make a sense.

There is compared an address stored in the pointer fn with the value 32 * ( sizeof( char ).

It seems you mean

if(fn==NULL || strlen( fn ) >=(32*sizeof(char))){

But if the condition indeed evaluates to true then your program has undefined behavior.
To check whether fn is equal to NULL you should do after the memory allocation as for example

fn = malloc(32 * sizeof(char));;
if ( fn != NULL )
{
    printf("what is your first name?\n");
    if ( scanf("%31s",fn) == 1 )
    {
        printf("This works.\n");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading