-2

Why am I getting a segmentation fault in this code ? I was attempting to initialize an array of structures.

#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
struct node{
        string data;
        int index;
        node(string data,int index):data(data),index(index){}
};
struct node **init_array(int n){
        struct node **array=(struct node **)malloc(n*sizeof(struct node *));
        for(int i=0;i<n;i++)
                *(array+i)=NULL;
        return(array);
}
struct node *init_node(string data,int index){
        struct node *t=(struct node *)malloc(sizeof(struct node));
        t->data=data;
        t->index=index;
        return(t);
}
int main(){
        node **array=init_array(5);
        *(array+0)=init_node("Debal",23);
        *(array+1)=init_node("Debdut",24);
        *(array+2)=init_node("Debojyoti",22);
        *(array+3)=init_node("Ditsa",29);
        *(array+4)=init_node("Divyani",10);
        cout << (*(array+3))->index;
}

I was expecting the structures to be initialized with NULL.

273K
  • 29,503
  • 10
  • 41
  • 64
  • 1
    First learn more C++ (your code is a mix of "C" and "C++" now), using malloc for C++ classes is not good (undefined behavior). Try rewriting your code using std::vector. [struct](https://www.learncpp.com/cpp-tutorial/introduction-to-structs-members-and-member-selection/), [vector](https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdvector/). Stop using `using namespace std;`. Where are you learning C++ from, because it doesn't seem to be a good source . – Pepijn Kramer Oct 31 '22 at 06:23

1 Answers1

0

You should not use malloc on types which have constructors (like std::string) because malloc will not call those constructors. Use new instead.

node* init_node(string data, int index)
{
    node* t = new node(data, index);
    return t;
}

There really is no need to use malloc in a C++ program.

john
  • 85,011
  • 4
  • 57
  • 81