Reputation: 1
I am trying to create a linked list that will store words and how many times they occurred in the .txt file. Before reading I'm trying to create a linked list to see if it is okay. While testing, it is crashing.
#include <iostream>
#include <string>
struct n {
std::string word;
int occurance;
n* next;
};
typedef n node;
int main() {
node* root;
root = (node*)malloc(sizeof(node*));
root->word = "test";
root->occurance = 5;
std::cout << root->word
<< root->occurance << std::endl;
}
Upvotes: 0
Views: 49
Reputation: 11350
root = (node*)malloc(sizeof(node*));
Is wrong in two ways. You should use
root = new node;
Firstly you code will allocate space for a node*
(usually 4 or 8 bytes) not for a node
.
Secondly malloc
only allocates memory, but doesn't initialize it. See also In what cases do I use malloc and/or new?1 That means all members of the newly allocated node
have indeterminate values and reading them will cause undefined behaviour.
In your case this manifests as access vioaltion.
1 In modern C++ you should avoid both ;)
Upvotes: 1
Reputation: 58909
sizeof(node*)
gets the size of a pointer to a node
. Probably 4 or 8 bytes. malloc(sizeof(node*))
allocates that many bytes.
But a node
is bigger than a pointer to a node
. So then your code fills in all the data and goes past the end of the memory it allocated because it only allocated enough space for a pointer.
Solution 1: change malloc(sizeof(node*))
to malloc(sizeof(node))
Solution 2: change (node*)malloc(sizeof(node*))
to new node
because it's C++ (not C) and you can do that.
Also, don't forget to free it (free(root);
for malloc
or delete node;
for new
). The OS automatically frees all your stuff when the program ends, so it's not important in this short program, but when you make a program that does a lot of stuff, you have to free the memory from one part so that the next part can reuse it.
Upvotes: 0
Reputation: 179991
malloc
is a holdover from C, which is how C developed back in the previous century. It compiles, but that's mostly bad luck.
Just move to at least 1998, and use std::list
, or perhaps std::map<std::string, int>
. Explaining why obsolete technology fails isn't that useful.
Upvotes: 0