Reputation: 13
I'm building a function that searches for a word in a word search matrix from left to right, and I'm getting an aborted(core dumped).
The function:
void lefttoright(int rowcol, char **matrix, char* find){
int i, j, k, q, len, count = 0;
len = strlen(find)+1;
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
char* correct = malloc(sizeof(char) * 20);
if (matrix[i][j] == find[0]){
for (q = j; q < rowcol; q++){
for (k = 0; k <= len; k++){
if (matrix[i][q] == find[k]){
correct[k] = matrix[i][q];
}
}
}
printf("%s\n", correct);
if (strcmp(correct, find) == 0){
count++;
free(correct);
}
}
else continue;
}
}
printf("%d", count);
}
Through print statements I've found that
if (matrix[i][j] == find[0]){
seems to be the problem, but I could be wrong. Any ideas? Thanks in advance.
Upvotes: 0
Views: 417
Reputation: 399833
One problem is clearly that you malloc()
always, even if there's no match. This will leak memory like crazy. Since you also don't NULL
-check your allocation, it's possible you run out of memory and then fail due to writing to a NULL
pointer.
You should run the program in a debugger to get a backtrace.
Upvotes: 1