简体   繁体   English

为什么我的C程序中出现“程序失败:内存故障,核心转储”?

[英]Why am I getting a “Program failed: Memory fault, core dumped” in my C program?

This program reads text from the standard input and builds a binary search tree containing the individual words from the input. 该程序从标准输入中读取文本,并构建包含输入中各个单词的二叉搜索树。 The program reads input until no more data is available, counting the frequency of occurrence of each word in the input. 程序读取输入,直到没有更多数据可用,计算输入中每​​个字的出现频率。 Once the input has been exhausted, the tree will be traversed with an in-order traversal to produce an alphabetical list of words with their frequencies. 一旦输入耗尽,将通过有序遍历遍历树以产生具有其频率的字母的字母列表。

Problem: I can compile my code without any errors and when I run ./wordFreq < input.1, it runs perfect and outputs the correct answer with no errors...this is the correct output: 问题:我可以编译我的代码而没有任何错误,当我运行./wordFreq <input.1时,它运行完美并输出正确答案而没有错误...这是正确的输出:

additional 1
agree 3
another 3
don't 3
for 1
I 1
input 4
is 3
line 5
need 1
one 1
road 1
the 1
think 1
This 4
we 1
yet 1
you 3

But whenever I submit it to the try server it tests the code and tells me that I didn't output anything, and that I had a "Program failed: Memory fault, core dumped", this is the output I am getting on page 1 : Try Submission Output 但每当我将它提交给try服务器时,它会测试代码并告诉我我没有输出任何东西,并且我有一个“程序失败:内存故障,核心转储”,这是我在第1页上得到的输出: 尝试提交输出

This is my wordFreq.c file: 这是我的wordFreq.c文件:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "wordFreq.h"

#define UNUSED(p)  ((void)(p))

// Creates a node for each unique word it is given, and then inserts this 
// new node in the proper position in the binary search tree, updating 
// whatever pointer is necessary.
//
// @param root a pointer to the variable which contains the pointer to the       
//               root-level node in the tree
// @param word a pointer to the NUL-terminated arrach of characters
void insert_word(TreeNode** root, const char *word){
    if (*root == NULL){
        *root = (TreeNode*)malloc(sizeof(TreeNode));
        unsigned int len = strlen(word);
        (*root)->word = (char *)malloc((len + 1) * sizeof(char));
        strncpy((*root)->word, word, len);
        (*root)->word[len] = 0;
        (*root)->frequency = 1;
        (*root)->left = NULL;
        (*root)->right = NULL;
    }
    else{
        int compare = strcasecmp(word, (*root)->word);
        if (compare < 0){
            insert_word(&((*root)->left), word);
        } else if(compare> 0){
            insert_word(&((*root)->right), word);
        } else if(compare == 0){
            (*root)->frequency++;
        }
    }
}

// Traverses the entire tree using an in-order traversal and will 
// print th contents of each node as it is visited
//
// @param root a pointer to the root node of the tree
void traverse_tree(const TreeNode* root){
    if (root == NULL)
        return;
    if (root != NULL){
        traverse_tree(root->left);
        printf("%s %d\n", root->word, root->frequency);
        traverse_tree(root->right);
    }
    return;
}

// Deallocates all the nodes that were created in insert_node()
//
// @param a pointer to the root node of the tree
void cleanup_tree(TreeNode* root){
    if (root == NULL)
        return;
    if (root->left != NULL){
        cleanup_tree(root->left);
    }
    if(root->right != NULL){
        cleanup_tree(root->right);
    }   
    free(root->word);
    free(root);
    return;
}

int main(int argc, char* argv[]){
    UNUSED(argv);
    if (argc > 1)
        printf("Usage: bst");
    else{
        FILE* pFile = fopen("input.1", "r");
        char *buf = NULL;
        size_t len = 0;
        TreeNode** root = NULL;
        if (!pFile){
            printf("File not found");
        } else{
            root = (TreeNode**)malloc(sizeof(TreeNode*));
            *root = NULL;
            while (getline(&buf,&len,pFile) > 0){
                char * pch;
                pch = strtok(buf, " !@#$%^&*?.,:;\n");
                while (pch !=NULL){
                    insert_word(root, pch);
                    pch = strtok(NULL, " !@#$%^&*,:;?.\n"); 
                }
            }
            free(buf);
            fclose(pFile);
            traverse_tree(*root);
        }
        cleanup_tree(*root);
        free(root);

    }
    return 0;   
}    

This is my wordFreq.h file: 这是我的wordFreq.h文件:

#ifndef _BST_H_
#define _BST_H_

// The definition of the tree structure
typedef struct TreeNode_st {
    char *word;                   // the word held in this node
    unsigned int frequency;       // how many times it has been seen
    struct TreeNode_st *left;     // node's left child
    struct TreeNode_st *right;    // node's right child
} TreeNode;

// FUNCTIONS ARE REQUIRED TO IMPLEMENT

// insert_word() 
//     Dynamically build BST by allocating nodes from the heap
//
// args -
//        root - a pointer to the pointer to the root of the tree
//               to build this tree on to.
//        word - string containing the word to be inserted

void insert_word( TreeNode** root, const char *word );

// traverse_tree()
//    Recursively traverses the tree and prints the value of each
//    node.
//
// args -
//        root - a pointer to the root of the tree to traverse

void traverse_tree( const TreeNode* root );

// cleanup_tree()
//    Cleanup all memory management associated with the nodes on the heap
//
// args
//      root - the current root of the tree

 void cleanup_tree( TreeNode* root );

 #endif // BST_H

This is the input file (named input.1): 这是输入文件(名为input.1):

This is one input line.
This is another input line, don't you agree?
Another input line, don't you agree?
This is yet another input line, don't you agree?
I think we need this additional line for the road.

Compile Commands: 编译命令:

root@comp:~/Desktop/Homeworks/5$ gcc -ggdb -std=c99 -Wall -Wextra -pedantic  -c wordFreq.c
root@comp:~/Desktop/Homeworks/5$ gcc -ggdb -std=c99 -Wall -Wextra -pedantic -o wordFreq wordFreq.o  -lm

Valgrind Test: I also tested the code in valgrind using the command: Valgrind测试:我还使用命令测试了valgrind中的代码:

I got no errors... here's the link to test on page 2 : Valgrind Test Link 我没有错误......这是第2页上的 测试链接Valgrind Test Link

You have some issues in your code: 您的代码中存在一些问题:

  • You include non-standard file <strings.h> , but not <stdlib.h> where malloc() and free() are declared. 您包含非标准文件<strings.h> ,但不包括<stdlib.h> ,其中声明了malloc()free()

  • You never check malloc() return value. 你永远不会检查malloc()返回值。 If the test system has very little memory or is configured to make malloc() fail early, which is doable, your program will crash instead of reporting the error. 如果测试系统内存很少或者配置为使malloc()提前失败,这是可行的,那么程序将崩溃而不是报告错误。

  • Do not use strncpy((*root)->word, word, len); 不要使用strncpy((*root)->word, word, len); to copy the string to allocated memory. 将字符串复制到已分配的内存。 Just use strcpy since you allocated enough memory with strlen(word) + 1 bytes, or use strdup() . 只使用strcpy因为你用strlen(word) + 1个字节分配了足够的内存,或者使用strdup() strncpy does not do what you think! strncpy不按你的想法strncpy it has very error prone and widely misunderstood semantics. 它容易出错并且被广泛误解为语义。 Never use this function. 切勿使用此功能。

  • In the main() function, you should use a TreeNode *root; main()函数中,您应该使用TreeNode *root; variable and pass its address to insert_word() instead of allocating a pointer. 变量并将其地址传递给insert_word()而不是分配指针。

The only serious issue is the second point above, although it is unlikely to explain the observed behavior. 唯一严重的问题是上面的第二点,尽管不太可能解释观察到的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在C中的多线程调度程序中出现分段错误(内核已转储) - Why is there segmentation fault(core dumped) in my multithreaded scheduling program in C 运行程序时出现分段错误(核心转储) - I am getting segmentation fault ( core dumped ) when I am running the program C-在此简单程序中获得分段错误(核心转储)错误 - C - Getting a segmentation fault(core dumped) error in this simple program 是什么导致我的 C 程序中出现此错误(分段错误(核心转储))? - What is causing this error in my C program (Segmentation fault (core dumped))? 为什么此C程序会导致分段错误(内核已转储)? - Why does this C program lead to a segmentation fault (core dumped)? 为什么分段错误(核心转储)错误适用于我的C程序? - Why does segmentation fault (core dumped) error apply to my C program? C中的文件I / O程序:Segmentation Fault(核心转储) - File I/O program in C: Segmention Fault (core dumped) 我的C程序中出现内存故障(coredump)错误消息? - I am getting an Memory fault(coredump) error message in my c program? 为什么我会遇到分段错误(核心转储)? - Why am I getting a segmentation fault (core dumped)? 为什么我收到分段错误(核心转储)消息? - Why am I getting Segmentation fault (core dumped) message?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM