Issues with points and char arrays.

I am attempting to build a wordcount program for a homework problem.
When I run my program I get a segmentation fault(core dumped) printed to the terminal.

I believe I know where the issue is but I do not understand how to resolve it. My code is as follows.

void WordCounts::tallyWords(string sentence)

int length = sentence.length();

char* str = new char[length + 1]; // create a new char array

strcpy(str, sentence.c_str()); // copy sentence into str

// splitting words using punctuations as delimeters

char* pointer = strtok (str," ,.-?><:;[]{}|/\"\'\\!");

while (pointer != NULL) // loop the char array
int i;
for( i = 0 ; i < index ; i++ )
// if word is found
if(word[i] == pointer)
// increase the count of word
// break out of loop
// if word was not found
if(i == index)

// add word

word[index] = pointer;
// set the count to 1

count[index] = 1;
pointer = strtok (NULL, " ,.-?><:;[]{}|/\"\'\\!");

From what I have read on other websites the usual issue is that my first pointer is not initialized to anything however,I thought that is what I was doing with these lines of code.

int length = sentence.length();
char* str = new char[length + 1];

but it does not seem to work. What might I be able to do differently to make this work?
Lookup strdup(), it'll save a few lines of prep code.

You have to use strcmp() to compare C strings (in char arrays).

You appear to be using global variables, work and index. You should pass these in as parameters.

Remember to free str.

Registered users can post here. Sign in or register to post.