-1

My little Program is build this way:

  • I have an Object Element that is defined as following:

    struct element {
        element* next;
    } typedef element;
    
  • My Program is calling this recursive function...

    int dosomething(element* a) {
        if (a != NULL)
            return dosomething(a->next);
        else
        return 0;
    }
    
  • In the main function:

    int main(void) {
        element* a = (element *) malloc(sizeof(element));
        a-> next = (element *) malloc(sizeof(element));
    
        cout << dosomething(a) << endl;
    
        return 0;
    }    
    

When running this Program, I get:

Segmentation fault: 11

So, a and a->next is defined. a->next->next should be NULL, so the function should just return 0?

Why isn't this working?

erip
  • 16,374
  • 11
  • 66
  • 121
Nicolas Brauch
  • 497
  • 1
  • 4
  • 10

3 Answers3

1

You would have to initialize the next-pointer with 0, otherwise it is uninitialized and "a != NULL" will not be true under some circumstances. You could use calloc instead of malloc, which initializes the memory with 0

Ctx
  • 18,090
  • 24
  • 36
  • 51
1

a->next->next is not NULL. ```malloc`` does not gurantee that the allocated memory region will be initialized to something (i.e. it has the value of what has previously been there).

Also, Do I cast the result of malloc?

int main(void) {
    element* a = (element *) malloc(sizeof(element));
    a-> next = (element *) malloc(sizeof(element));
    a->next->next = NULL;

    cout << dosomething(a) << endl;

    return 0;
}  
Community
  • 1
  • 1
Paul92
  • 8,827
  • 1
  • 23
  • 37
0

You weren't making the last element NULL - malloc doesn't do this for you. You should use C++ constructs, too. They're very helpful.

#include <iostream>

struct Element {
  Element* next;
};

int do_something(Element* a) {
  if(a) {
    do_something(a->next);
  }
  return 0;
}

int main() {
  Element* last = NULL;
  Element* next = new Element;
  next->next = last;
  Element* first = new Element;
  first->next = next;
  std::cout << do_something(first) << std::endl;
  delete first;
  delete next;
  delete last;
  return 0;
}

ideone

erip
  • 16,374
  • 11
  • 66
  • 121