简体   繁体   中英

Getting Segmentation fault from printf

So basically i wrote 2 functions, to set a min and max number from input_array, in which both i would like to implement a code to return "-1" when NULL is called instead of input_array. The code looks like this.

#include <stdio.h>
#include <math.h>
int array_min(const int input_array[], const int array_size);
int array_max(const int input_array[], const int array_size);
int main(){
        int input_array[]={1,12,3,43,5};
        printf("%d\n", array_min(input_array, 5));
        printf("%d\n", array_max(input_array, 5));
        printf("%d\n", array_max(NULL, 5));
}
int array_min(const int input_array[], const int array_size){
        int min = input_array[0];
        for(int i=1; i<array_size; i++){
                if( input_array[i] < min){
                        min = input_array[i];
                }
        }
        return min;
}
int array_max(const int input_array[], const int array_size){
        int max = input_array[0];
        for(int a=1; a<array_size; a++){
                if(input_array == NULL){
                        return -1;
                }
                else{
                        if(input_array[a]>max){
                                max = input_array[a];
                        }
                }
        }
        return max;
}

I tried to set max to -1 also but the result was the same, the program got compiled, but instead of the desired output of -1 it was "Segmentation fault". What would be the best way to implement it to both the min and max functions?

The problem is, before checking for incoming NULL , you're dereferencing the pointer

 int max = input_array[0];

do that after your have validated the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM