संकलक निम्नलिखित कोड पर क्रम segfault फेंकता का उपयोग कर इसके निर्माण के बाद अपने काम पर विभाजन गलती का कारण बनता है:स्ट्रिंग मान युक्त struct गतिशील स्मृति आवंटन
#include <iostream>
#include <string>
using namespace std;
struct Node{
int data;
void *next;
string nodeType;
};
Node* initNode(int data){
Node *n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = NULL;
n->nodeType = "Node"; //if this line is commented it works else segfault
return n;
}
int main() {
Node *n1 = initNode(10);
cout << n1->data << endl;
}
किसी कृपया समझा क्यों स्ट्रिंग काम एक struct के अंदर काम नहीं करता है जो गतिशील रूप से आवंटित किया गया है जहां स्थिर आवंटन के मामले में यह क्यों काम करता है?
निम्नलिखित तरीके के रूप में जहां यह काम करता है:
Node initNode(string data){
Node n;
n.data = data; //This works for node creation statically
n.next = NULL;
n.nodeType = "Node"; //and even this works for node creation statically
return n;
}
और फिर मुख्य समारोह में:
int main() {
Node n2 = initNode("Hello");
cout << n2.data << endl;
}
'malloc' बस स्मृति आवंटित करता है, यह * ऑब्जेक्ट उदाहरण * निर्माण नहीं करता है, जिसका अर्थ है 'स्ट्रिंग' कन्स्ट्रक्टर नहीं कहा जाता है। –
अंगूठे का सामान्य नियम: सी ++ में सी के 'मॉलोक' का उपयोग न करें, 'नया' का उपयोग करें, और वास्तव में यदि संभव हो तो 'new' का उपयोग न करें, और 'make_shared' या' std :: unique_ptr' (C + +11) –