You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boggle搜索程序段错误咨询:调试正常但常规运行仍出错

Boggle搜索程序段错误问题排查

我在实现Boggle搜索程序时遇到了segmentation fault(段错误),推测问题与main函数中的path字符串有关。递归遍历棋盘时path需追加字符,更换新起点时path需重置为空,但不知如何实现。修改代码后,调试模式下程序可正常运行,但常规运行时仍出现段错误。

修改前代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "hash.h"

#define MAX_WORD_LENGTH 30

int wordcount = 0;
int row[] = { -1, -1, -1, 0, 1, 0, 1, 1 };
int col[] = { -1, 1, 0, -1, -1, 1, 0, 1 };

HashTable readwords(HashTable H, char *filename) {
    char word[50] = "";
    FILE *f = fopen(filename, "r");
    while (fscanf(f, " %s", word) != EOF)
        Insert(word, H);
    fclose(f);
    return H;
}

void readboard(char *filename, char board[][4]) {
    FILE *file;
    char line[12];
    // Open the file
    file = fopen(filename, "r");
    if (file == NULL) {
        printf("Error opening the file.\n");
        return;
    }
    int x = 0;
    // Read the file and populate the board dynamically
    while (fgets(line, sizeof(line), file) != NULL && x < 4) {
        board[x][0] = line[0];
        board[x][1] = line[2];
        board[x][2] = line[4];
        board[x][3] = line[6];
        x++;
    }
    // Close the file
    fclose(file);
}

bool isSafe(int x, int y, bool processed[][4]) {
    return (x >= 0 && x < 4) && (y >= 0 && y < 4) && !processed[x][y];
}

void searchBoggle(char board[][4], HashTable words, char answer[200][30],
                  bool processed[][4], int x, int y, char *path,
                  int wordX[30], int wordY[30]) {

    // marca o nó atual como processado
    processed[x][y] = true;
 
    // atualiza o caminho com o caractere atual e o insere no conjunto
    strncat(path, &board[x][y], 1);
 
    // verifica se o caminho está presente no conjunto de entrada
    if (Find(path, words)) {
        wordcount++;
        int sz = strlen(path);
        for (int j = 0; j < sz; j++) {
            answer[wordcount][j] = path[j];
        }
    }
    
    // verifica todos os oito movimentos possíveis da célula atual
    for (int k = 0; k < 8; k++) {
        // pula se uma célula é inválida ou já foi processada
        if (isSafe(x + row[k], y + col[k], processed)) {
            searchBoggle(board, words, answer, processed,
                         x + row[k], y + col[k], path, wordX, wordY);
        }
    }
    
    // backtrack: marca o nó atual como não processado
    processed[x][y] = false;
}

int main() {
    char path[30] = "";
    char filename[] = "corncob_caps_2023.txt";
    char filename2[] = "boggle0.txt"; 
    int tableSize = 60000; 
    char answer[200][30];
    bool processed[4][4];
    int wordX[30];
    int wordY[30];
    char board[4][4];
    HashTable words = InitializeTable(tableSize);
    words = readwords(words, filename);
    
    readboard(filename2, board);
    for (int x = 0; x < 4; x++) {
        for (int y = 0; y < 4; y++) {
            // considera cada caractere como um ponto de partida e executa o DFS
            searchBoggle(board, words, answer, processed, x, y, path, wordX, wordY);
        }
    }
    return 0;
}

修改后代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "hash.h"

#define MAX_WORD_LENGTH 30
int wordcount=0;
int row[] = { -1, -1, -1, 0, 1, 0, 1, 1 };
int col[] = { -1, 1, 0, -1, -1, 1, 0, 1 };

HashTable readwords(HashTable H,char *filename){
    char word[50]="";
    FILE* f = fopen(filename, "r");
    while(fscanf(f, " %s", word) != EOF)
        Insert(word, H);
    fclose(f);
    return H;
}

HashTable readCharsWords(HashTable H,char *filename){
    char word[50]="";
    int sz;
    FILE* f = fopen(filename, "r");
    while(fscanf(f, " %s", word) != EOF){
        char d[30];
        sz = strlen(word);
        memset(d, 0, sizeof(d));
        for (int j = 0; j < sz-1; j++) {
            d[j]=word[j];
            d[j+1]='\0';
            if(!Find(d,H)){
                Insert(d,H);
            }    
        }
        
    }
    fclose(f);
    return H;
}

void readboard(char *filename,char board[][4]) {
    FILE *file;
    char line[12];
    // Open the file
    file = fopen(filename, "r");
    if (file == NULL) {
        printf("Error opening the file.\n");
        return;
    }
    int x=0;
    // Read the file and populate the board dynamically
    while (fgets(line, sizeof(line), file) != NULL&&x<4) {
        board[x][0] = line[0];
        board[x][1] = line[2];
        board[x][2] = line[4];
        board[x][3] = line[6];
        x++;

    }
    // Close the file
    fclose(file);

    
}
bool isSafe(int x, int y, bool processed[][4]) {
    return (x >= 0 && x < 4) && (y >= 0 && y < 4) &&
        !processed[x][y];
}

void searchBoggle(char board[][4], HashTable halfwords, HashTable words, char answer[200][30], bool processed[][4], int x, int y, char *path, int wordX[30], int wordY[30],int len){
    // marca o nó atual como processado
    processed[x][y] = true;
 
    // atualiza o caminho com o caractere atual e o insere no conjunto
    path[len] = board[x][y]; path[len + 1] = '\0';
 
    // verifica se o caminho está presente no conjunto de entrada
    if (Find(path, words) && wordcount < 200) {
        strcpy(answer[wordcount++], path);
    }
    
    if(!Find(path, halfwords)){
        return;
    }
    
    // verifica todos os oito movimentos possíveis da célula atual
    for (int k = 0; k < 8; k++)
    {
        // pula se uma célula é inválida ou já foi processada
        if (isSafe(x + row[k], y + col[k], processed)) {
            searchBoggle(board, halfwords, words, answer, processed, x + row[k], y + col[k], path,wordX,wordY,len + 1);
        }
    }
    
    // backtrack: marca o nó atual como não processado
    processed[x][y] = false;
}

int main(){
    char path[30]="";
    char filename[] = "corncob_caps_2023.txt";
    char filename2[] = "boggle0.txt"; 
    int tableSize = 60000; 
    HashTable H = InitializeTable(200000);
    H=readCharsWords(H,filename);
    char answer[200][30];
    bool processed[4][4];
    int wordX[30];
    int wordY[30];
    char board[4][4];
    HashTable words = InitializeTable(tableSize);
    words = readwords(words, filename);
    
    readboard(filename2, board);
    for (int x = 0; x < 4; x++){
        for (int y = 0; y < 4; y++) {
            // considera cada caractere como um ponto de partida e executa o DFS
            searchBoggle(board,H,words,answer,processed, x,y, path,wordX,wordY,0);
            
        }
    }
    
    return 0;
}

内容的提问来源于stack exchange,提问作者L1nK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:47:02