0

I have a problem in my program which should prompt the user to enter number and the program will heapify them. The program runs but shows a runtime error after inserting the first number. I tried to fix it multiple times but in vain. If anyone could point to the precise error in the code it would be much appreciated. Thanks in advance. =) Anyways, here's the code:

#include <stdio.h>
void insert_node(int arr[], int max){
    if(max<15){
        printf("Type the number to insert: ");
        scanf("%d", arr[max]);  
        max++;
        }
    else
    printf("Error. The heap is full!");
}
void printheap(int arr[], int max){
    int count;  
    if(max>=1){
        printf("\nPrinting the Heap:");
        for(count==0;count<=max;count++)
        printf(" %d", arr[count]);
    }
}
void heapSort(int arr[], int max) {
    int i=0,temp,lc,rc; 
    while(i!=max-1){
        lc=2i+1;
        rc=2i+2;
        if(arr[i]<arr[lc]){ 
            temp=arr[i];
            arr[i]=arr[lc];
            arr[lc]=temp;
        }
        else if(arr[i]<arr[rc]){
            temp=arr[i];
            arr[i]=arr[rc];
            arr[rc]=temp;
        }   
        i=i+1;
    }
}
int main(int argc, char *argv[]){
    int arr[15];
    int max=0;  
    char ch;
    while(ch!='n' && ch!='N'){
        printheap(arr,max);
        insert_node(arr,max);   
        if(max>1)
            heapSort(arr,max);
        printf("\nInsert another key (y:yes/n:no)?  ");
        scanf("%c", &ch);
    }
    return 0;
}
Yacine
  • 9
  • 1
  • 6
  • 1
    Welcome to Stack Overflow! It sounds like you may need to learn how to use a [debugger](https://en.wikipedia.org/wiki/Debugger) to step through your code. With a good debugger, you can execute your program line by line and see where it is deviating from what you expect. This is an essential tool if you are going to do any programming. Further reading: [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Paul R May 02 '17 at 00:23
  • 2
    1) `lc=2i+1; rc=2i+2;` --> `lc=2*i+1; rc=2*i+2;` – BLUEPIXY May 02 '17 at 00:26
  • 2
    2) `scanf("%d", arr[max]);` --> `scanf("%d", &arr[max]);` – BLUEPIXY May 02 '17 at 00:27
  • 2
    3) `scanf("%c", &ch);` --> `scanf(" %c", &ch);` – BLUEPIXY May 02 '17 at 00:29
  • 2
    4) `count==0;` --> `count=0;` – BLUEPIXY May 02 '17 at 00:31
  • 2
    5) `insert_node(arr,max);` --> `insert_node(arr,max++);` – BLUEPIXY May 02 '17 at 00:34
  • 2
    6) `count<=max` --> `count – BLUEPIXY May 02 '17 at 00:35
  • 2
    7) It's wrong logic. – BLUEPIXY May 02 '17 at 00:38
  • @bluepixy thank you for helping me and sorry for wasting your time. but can you be more specific please? – Yacine May 02 '17 at 00:40
  • 2
    Read [Heapsort](https://en.wikipedia.org/wiki/Heapsort) – BLUEPIXY May 02 '17 at 00:50
  • for ease of readability and understanding: 1) separate code blocks (for, if, else, while, do...while, switch, case, default) via a single blank line. 2) separate functions by 2 or 3 blank lines (be consistent) 3) consistently indent the code: indent after every opening brace '{', unindent before every closing brace '}' suggest each indent level be 4 spaces. – user3629249 May 03 '17 at 14:37
  • when calling `main()`, and the parameters are not going to be used, then use the signature: `int main( void )` – user3629249 May 03 '17 at 14:38
  • there are several problems in the posted code, (which the compiler can output messages about) When compiling, always enable all the warnings, then fix those warnings. (for `gcc`, at a minimum use: `-Wall -Wextra -pedantic` I also use: `-Wconversions -std=gnu11` ) – user3629249 May 03 '17 at 14:46
  • for ease of readability and understanding, follow the axiom: *only one statement per line and (at most) one variable declaration per statement.* – user3629249 May 03 '17 at 14:48
  • when calling any of the `scanf()` family of functions, always check the returned value (not the parameter value) to assure the operation was successful – user3629249 May 03 '17 at 14:58
  • when wanting a sub function to modify a variable, the address of the variable must be passed to the sub function, not the contents of the variable I.E. in function: `main()`, the variable `max` is initialized to 0 and never incremented, – user3629249 May 03 '17 at 15:02
  • in the function: `heapSort()`, the value `max` could be 14, and when `max` = 14, then `i` could be as large as 13. then the calculation of `lc` results in 27 and the calculation of `rc` results in 28, BUT the arr[] only has a max of 15 positions (offset 0...14) so this (and similar) statement: `if( arr[i] < arr[lc] )` is accessing beyond the end of the array. This results in undefined behavior and can lead to a seg fault event – user3629249 May 03 '17 at 15:08
  • in the function: `printfheap()`, this line: `for( count==0; count<=max; count++ )` will result in accessing beyond the current number of entries in the array `arr[]` this means accessing uninitialized entriess (or even beyond the end of the array. Either case is undefined behavior and can lead to a seg fault event. And `==` is a comparison operator and what is wanted is `=`, an assignment operator. Suggest using: `for( count=0; count – user3629249 May 03 '17 at 15:13
  • strongly suggest, for readability of the code, that function names be formatted 'lowerCamelCase' I.E. the first word is lower case, each following word start with a capital letter, Using underscores between words makes the code more difficult to read/understand (and is a nuisance to type when writing these comments. One important thing to note: the compiler doesn't really care about inconsistent capitalization, as long as it is the same throughout the code. However, humans really work much better with consistency. – user3629249 May 03 '17 at 15:17
  • in function: `main()`, this line: `while(ch!='n' && ch!='N')` is checking the value of a variable on the stack, before that variable has been initialized/assigned, so the value of `ch` could be anything, including 'n' or 'N'. Such checking before initialization is undefined behavior – user3629249 May 03 '17 at 15:22
  • this line: `scanf("%d", arr[max]);` is passing the contents of `arr[max]` to the `scanf()` function, where the function is expecting the address of the item. Suggest: `scanf( "%d", &arr[max] );` notice the 'addressof' `&` operator – user3629249 May 03 '17 at 15:25
  • there is plenty more wrong with the posted code (and when handling a 'error' returned value from `scanf()` should use `exit( EXIT_FAILURE );` so should have the statement: `#include ` Remember, code is read by humans, so should be formatted to be very readable. – user3629249 May 03 '17 at 15:27

0 Answers0