【问题标题】:Why am I getting a "Program failed: Memory fault, core dumped" in my C program?为什么我的 C 程序中出现“程序失败:内存故障,核心转储”?
【发布时间】:2017-02-21 20:40:09
【问题描述】:

此程序从标准输入中读取文本,并构建一个包含输入中各个单词的二叉搜索树。程序读取输入直到没有更多数据可用,计算输入中每​​个单词的出现频率。一旦输入被用尽,树将按顺序遍历以生成按字母顺序排列的单词及其频率列表。

问题:我可以编译我的代码没有任何错误,当我运行 ./wordFreq 附加 1 同意 3 另一个 3 不要3 1 我 1 输入 4 是 3 第 5 行 需要 1 一个 1 1号路 1 认为 1 这 4 我们 1 还是 1 你 3

但是每当我将它提交到 try 服务器 时,它会测试代码并告诉我我没有输出任何东西,并且我有一个“程序失败:内存错误,核心转储”,这是我在 第 1 页 上得到的输出: Try Submission Output

这是我的 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;   
}    

这是我的 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

这是输入文件(名为 input.1):

这是一根输入线。 这是另一条输入线,你不同意吗? 另一个输入行,你不同意吗? 这是另一个输入行,你不同意吗? 我认为我们需要这条额外的道路。

编译命令:

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 测试:我还使用以下命令测试了 valgrind 中的代码:

我没有发现任何错误...这是 第 2 页上的测试链接: Valgrind Test Link

【问题讨论】:

  • 如果相同的代码暴露了两种不同的行为,我怀疑是鼻恶魔。
  • 您是否认真地在您的系统上以root 进行编程?
  • @chqrlie 不,我只是出于保密目的更改了它
  • 如果您想删除用户名,请使用ShaolinGOD 或一些普通的用户名(guestuser...),但不要让新手认为可以登录和工作作为根。
  • @chqrlie 我的错,下次记得!

标签: c linux gcc memory-leaks gcc-warning


【解决方案1】:

您的代码中有一些问题:

  • 您包括非标准文件&lt;strings.h&gt;,但不包括&lt;stdlib.h&gt;,其中声明了malloc()free()

  • 您永远不会检查 malloc() 返回值。如果测试系统内存非常少或配置为使malloc()提前失败,这是可行的,你的程序将崩溃而不是报告错误。

  • 不要使用strncpy((*root)-&gt;word, word, len); 将字符串复制到分配的内存。只需使用strcpy,因为您使用strlen(word) + 1 字节分配了足够的内存,或者使用strdup()strncpy 不会按照你的想法去做!它具有非常容易出错且被广泛误解的语义。切勿使用此功能。

  • main() 函数中,您应该使用TreeNode *root; 变量并将其地址传递给insert_word(),而不是分配指针。

唯一严重的问题是上面的第二点,尽管它不太可能解释观察到的行为。

【讨论】:

  • @ShaolinGOD:将malloc()返回值存储到指针中后,测试该指针是否为NULL并正常退出函数或显示错误消息中止,因为这表明内存不足.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多