user2128572
user2128572

Reputation: 21

Segmentation Fault on map inside structure

I am creating a structure which contains map but when I try to insert an element , It throws segmentation fault

#include<stdio.h>
#include<stdlib.h>
#include<map>
using namespace std;
typedef struct a
{
    map<int,int> m;
}a;
int main()
{
    a* b;
    b=(a*) malloc(sizeof(a));
    b->m[0]=0;

 }

Upvotes: 0

Views: 650

Answers (2)

Tuxdude
Tuxdude

Reputation: 49473

Use the new operator to dynamically allocate memory otherwise the map's constructor within the struct will not be invoked when using malloc.

int main()
{
    a* b;
    b= new a;

    b->m[0]=0;
    // Do whatever here

    // When you're done using the variable b
    // free up the memory you had previously allocated
    // by invoking delete
    delete b;

    return 0;
}

Upvotes: 2

us2012
us2012

Reputation: 16253

None of your code even starts to resemble idiomatic C++, the best thing anyone can recommend to you is to pick up a good book about C++.

A quick fix for your program: Use new instead of malloc - malloc doesn't belong in C++ code. That will make sure that a->m is actually constructed. Then, be sure to delete b at the end. This comes with all the problems of new/delete, so when you know a little more about the basics of C++, read up on smart pointers.

A slightly more drastic change, that will result in less problems in your simple program: Use automatic storage:

a b;
b.m[0] = 0;

This would be your program in C++ rather than the weird C/C++ mix:

#include<map>

struct a
{
    std::map<int,int> m;
};

int main()
{
    a b;
    b.m[0]=0;
}

Upvotes: 7

Related Questions