Hi, I need help with this
I have an Struct like this:
struct nodo
{ char *str1;
char *str2;
set<char*> dominio;
nodo *anterior,*siguiente;
};nodo *primero,*ultimo,*nuevo,*actual;
ok, when i create a new node (nodo), try to insert a new element to the set, dominio, and i got an error of segmentation fault.
this is the function to add the info:
void agregar(char* pch)
{ nuevo = (nodo*)malloc(sizeof(nodo));
nuevo -> str1 = (char*)malloc(strlen(pch));
nuevo -> str2 = (char*)malloc(strlen("ole2"));
You can't use malloc() to allocate a new nodo struct; you have to use new. The difference
between malloc and new is that new runs constructors; malloc does not. set<char*> is
a class that has a constructor that must be run prior to attempting to use the set.
ok, but i have try to do it with new nodo and i can't to assign values to nuevo->str1 e nuevo->str2. That's mean, if i use new nodo() i got a segmentation fault when try to do this
With C++ we are get an excellent mechanism - constructors! Please use it.
Operator new implicitly calls constructor for classes and it is preferred way
for creation objects dynamically.
Though initial values of str1 and str2 nonsignificant in creation(however it is a good practice initialize pointers with NULL) but dominio member need to be constructed.
That's right way:
nuevo = new nodo;
Or unreasonable way:
1 2 3 4 5 6 7 8 9 10 11
struct nodo
{
char *str1;
char *str2;
set<char*> *dominio;
nodo *anterior,*siguiente;
};
nuevo = (nodo*)malloc(sizeof(nodo));
nuevo->dominio = new set<char*>;
nuevo->dominio->insert(pch);
And in conclusion about segmentation fault. Strlen return string length without null-character ;-)
1 2
nuevo -> str1 = (char*)malloc(strlen(pch)+1);
nuevo -> str2 = (char*)malloc(strlen("ole2")+1);
There is another way to do it. However I think the aim of the exercise is to teach you about pointers and memory...when you new the struct, it only creates the memory for the struct. If the struct has pointers you have to allocate memory for whatever those pointers are pointing to. Or if you want to share the memory from another already allocated object, simply assign it into the struct memory. Though, with sharing pointers, you may have to think about dangling pointers.