user3409814
user3409814

Reputation: 245

Runtime Error in C

I run this program in Ideone.com and get a runtime error. Could anyone suggest softwares to debug runtime errors in Linux. EVerytime asking such doubts on stackoverflow will be avoided

#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
    int num;
    struct Node *next;
}Node;

void push(Node **head,int num){
    Node *newnode = (Node *)malloc(sizeof(Node));
    newnode->num = num;
    newnode->next = *head;
    *head = newnode;
}

void palindrome(Node **front){
    int *res = 1;
    isPalindrome(front,*front,res); 
    if(*res == 0)
        printf("Not a Palindrome");
    else
        printf("Palindrome");
}

void isPalindrome(Node **front,Node *back,int *res){
    if(back == NULL)
        return;
    isPalindrome(front,back->next,res);
    if(*res == 0)
        return;
    if((*front)->num != back->num)
        *res = 0;
    *front = (*front)->next;
}

int main(void){
    Node *head = NULL;
    push(&head,1);
    push(&head,2);
    push(&head,2);
    push(&head,1);
    palindrome(&head);
    return 0;
}

Upvotes: 0

Views: 417

Answers (4)

deeiip
deeiip

Reputation: 3379

int *res = 1;

Firstly this line should throw an error. Syntactically correct would be

int *res = (int*)1;

Even now you'd get undefined behaviour because you've not got res via malloc. And in later part you're doing this.

Upvotes: 0

Bahattin Ungormus
Bahattin Ungormus

Reputation: 713

You have a problem in your palindrome function on the line:

int *res = 1;

You're setting the value of the pointer to 1 instead of the value of the variable. It should be,

int res = 1;

and then when you call isPalindrome you should do:

isPalindrome(front,*front, &res);

Upvotes: 1

piokuc
piokuc

Reputation: 26184

The standard debugger on Linux: gdb.

To debug a C or C++ program you should compile it with -g option first and, preferably, switched off optimization: -O0.

gdb is a command line program, working in text mode. There is a few graphical debuggers for Linux, too, they are usually just GUI for gdb. Use your favourite Internet search engine to find them.

Upvotes: 2

Roman
Roman

Reputation: 199

I think your method palindrome should look like this:

void palindrome(Node **front){
  int res = 1;
  isPalindrome(front,*front,&res); 
if(res == 0)
    printf("Not a Palindrome");
else
    printf("Palindrome");
}

In your implementation of this method you first creating pointer to int and assign it memory address 0x0000001 and then you dereference it that causes runtime error.

Upvotes: 1

Related Questions