Search code examples
arrayscscanfdynamic-memory-allocationc-strings

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.


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");
        }
    }