Creating a function the returns frequency of given words in C++
An answer to this question on Stack Overflow.
Question
OK so I am not sure what is causing me to get the error
segmentation fault (core dumped)
But I get it every time I run my program. If someone could please explain what I am doing wrong that would be great.
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
void frequency(char* paragraph, string words[],int num_words){
//Declare the required variables.
string temp = "";
int freq[num_words];
//Start the loop to set the frequency of each word to 0.
for(int i=0;i<num_words;i++){
freq[i] = 0;
}
//Start the loop to traverse the paragraph.
for(int i=0;i<=strlen(paragraph);i++){
//Check the string if a space or null is found.
if(paragraph[i] == ' ' || paragraph[i] == '\0'){
//Start the loop to compare each word.
for(int j=0;j<num_words;j++){
int flag = 0;
//Start the loop to comapare the word.
for(int k=0;k<words[j].length();k++){
//Convert both the characters to lowercase to compare ignoring the case.
if(tolower(temp[k]) != tolower(words[j].at(k))){
//Break the loop if the character does not match.
flag = 1;
break;
}
}
//Increase the frequency if the word matches with the current string.
if(flag == 0)
freq[j]++;
}
//Reset the string.
temp = " ";
}
//Otherwise, append the character in the string.
else{
temp = temp+paragraph[i];
}
}
//Start the loop to print the frequency of each word.
for(int i=0;i<num_words;i++){
cout<<words[i]<<": "<<freq[i]<<endl;
}
}
int main()
{
char *paragraph;
string *words;
string swords;
cout << "Enter the paragraph: ";
cin.getline(paragraph, 250);
cout << "Enter the words to search: ";
getline(cin, swords);
int spaces = 0;
//Start the loop to count the number of words.
for(int i = 0; i < swords.length(); i++){
if(swords.at(i) == ' ')
spaces++;
}
int num_words = spaces + 1;
int pos = 0;
string temp = " ";
//Create an array of strings to store the words.
words = (string*) new string[num_words];
//Start the loop to store the words in the array.
for(int i = 0; i < swords.length(); i++)
{
//Store the string in the array if a space is encountered.
if(swords.at(i) == ' ')
{
words[pos] = temp;
temp = " ";
++pos;
}
//Otherwise, append the character in the string.
else
{
temp += swords.at(i);
}
}
//Store the last string in the array.
words[pos] = temp;
//Call the function to compute and display the frequency.
frequency(paragraph, words, num_words);
//Return 0 and exit the code.
return 0;
}
I am aware that Segmentation faults mostly occur because you are trying to access memory that you don't have permission to (Usually by setting a variable to null or something similar) but I can't for the life of me find the error in my own code. If you can offer me any assistance please do
Answer
Compile your code with:
g++ -g -fsanitize=address main.cpp
And then run it.
The program will then exit on the line causing the segmentation fault and tell you what memory it tried to access that caused the issue.