我得到无效免费和内存泄漏.这是我的代码:
/*=============================================================================
  |
  |  Assignment:  Test #2

  |        Class:  Programming Basics
  |         Date:  December 20th,2017
  |
  |     Language:  GNU C (using gcc),OS: Arch Linux x86_64)
  |     Version:   0.0
  |   To Compile:  gcc -Wall -xc -g -std=c99 kontrolinis2.c -o kontrolinis_2
  |
  +-----------------------------------------------------------------------------
  |
  |  Description:  The program which gets the input number,which indicates how
  |                many words there will be,then prompts the user to enter
  |                those words,and then displays a histogram in descending 
  |                order by times the word is repeated. The words with the 
  |                same duplicate count are sorted in lexicographical order
  |
  +===========================================================================*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "dbg.h"
#include "lib_riddle.h"

#define MAX_STRING 50

// Frequency structure. Contains the word and the times
// it is repeated
typedef struct Freq {
    char* word;
    int times;
} Freq;

// Histogram structure. Contains the list of frequencies (struct)
// and the size of the list.
typedef struct Histogram {
    Freq** freqs;
    int size;
} Histogram;

// sort the portion of the given array of frequency structs
// in lexicographically reverse order (from z to a) by Freq->word attribute.
//
// ::params: target - array continaing frequency structs
// ::params: first - first index of the portion of the array
// ::params: last - last index of the portion of the array
// ::return: Array of frequency structs (portion of which is
// sorted in lexicographically reverse order)
Freq** sort_rlexicographical(Freq** target,int first,int last);

// sort the frequency structs array by their Freq->times
// attribute,using quicksort
//
// ::params: target - the frequency array
// ::params: first - first index of the array
// ::params: first - last index of the array
// ::return: Sorted array of frequency structs
Freq** quicksort_freqs(Freq** target,int last);

// print Frequency array in reverse order,which displays
// the data as in historgram (from bigger to smaller)
//
// ::params: target - the frequency array
// ::params: size - size of the array
void print_reverse(Freq** target,int size);



int main(int argc,char* argv[])
{

    // get number from the user
    int size = get_pos_num("Please enter a number of words > ",0);

    Histogram* histogram = malloc(sizeof(Histogram));
    histogram->freqs = malloc(size * sizeof(Freq*));
    histogram->size = 0;

    char** words = (char**)malloc(size * sizeof(char*));
    for (int i = 0; i < size; i++) {
        words[i] = (char*)malloc(MAX_STRING * sizeof(char));
    }

    // get words from the user
    for (int i = 0; i < size; i++) {
        words[i] = get_word("Enter word > ",words[i]);
    }

    int duplicates;
    int is_duplicate;
    int hist_size = 0;

    // initialize the array of duplicates
    char** duplicated = (char**)malloc(size * sizeof(char*));
    for (int i = 0; i < size; i++) {
        duplicated[i] = (char*)calloc(MAX_STRING+1,sizeof(char));
        /*duplicated[i] = (char*)malloc(MAX_STRING);*/
        /*duplicated[i] = (char*)calloc(MAX_STRING + 1,sizeof(char));*/
    }

    // count the duplicates of each word and add the word with its duplicate count
    // to the frequency array,and then - to the histogram struct. Each word is
    // writtern once,without duplication.
    for (int i = 0; i < size; i++) { 
        is_duplicate = 0;

        // if the word is already added to the duplicate list,// it means that its duplicates are already counted,// so the loop iteration is skipped
        for (int k = 0; k < size; k++) {
            if (strcmp(duplicated[k],words[i]) == 0) {
                is_duplicate = 1;
            }
        }

        // skipping the loop iteration
        if (is_duplicate) {
            continue;
        }

        // found the word about which we are not yet sure
        // whether it has any duplicates.
        duplicates = 1;
        Freq* freq = malloc(sizeof(Freq));
        freq->word = (char*)malloc(sizeof(MAX_STRING * sizeof(char)));
        freq->word = words[i];
        // searching for the duplicates
        for (int j = i + 1; j < size; j++) {
            if (strcmp(words[i],words[j]) == 0) {
                // in case of a duplicate
                // put word in duplicates array
                // and increase its duplicates count
                duplicated[i] = words[i];
                duplicates++;
            }
        }
        freq->times = duplicates;
        histogram->freqs[histogram->size++] = freq;
        hist_size++;
    }

    debug("Frequency table:");
    for (int i = 0; i < hist_size; i++) {
        debug("%s %d",histogram->freqs[i]->word,histogram->freqs[i]->times);
    }
    debug("-----------------------");

    histogram->freqs = quicksort_freqs(histogram->freqs,hist_size - 1);

    debug("Sorted frequency table:");
    for (int i = hist_size - 1; i >= 0; i--) {
        debug("%s %d",histogram->freqs[i]->times);
    }
    debug("-----------------------");

    int max_count = histogram->freqs[hist_size - 1]->times;
    int index = hist_size - 1;
    int index_max;

    // partition the frequency array by the same duplicate times,and
    // pass the partitioned array to reverse lexicographical sort
    // on the go.
    for (int i = max_count; i > 0 && index >= 0; i--) {
        index_max = index;
        if (histogram->freqs[index]->times == i) {
            while (index - 1 >= 0 && histogram->freqs[index - 1]->times == i) {
                index--;
            }
            if (index != index_max) {
                histogram->freqs = sort_rlexicographical(
                    histogram->freqs,index,index_max);
            }
            index--;
        }
    }

    printf("\nLexicographically sorted frequency table:\n");
    print_reverse(histogram->freqs,hist_size);




    for (int i = 0; i < size; i++) {
        free(duplicated[i]);
    }
    free(duplicated);

    for (int i = 0; i < size; i++) {
        free(words[i]);
    }
    free(words);

    for (int i = 0; i < hist_size; i++) {
        free(histogram->freqs[i]->word);
    }

    for (int i = 0; i < hist_size; i++) {
        free(histogram->freqs[i]);
    }
    free(histogram->freqs);
    free(histogram);


    return 0;
}

Freq** quicksort_freqs(Freq** target,int last)
{
    Freq* temp;
    int pivot,j,i;

    if (first < last) {
        pivot = first;
        i = first;
        j = last;

        while (i < j) {
            while (target[i]->times <= target[pivot]->times && i < last) {
                i++;
            }
            while (target[j]->times > target[pivot]->times) {
                j--;
            }
            if (i < j) {
                temp = target[i];
                target[i] = target[j];
                target[j] = temp;
            }
        }
        temp = target[pivot];
        target[pivot] = target[j];
        target[j] = temp;

        quicksort_freqs(target,first,j - 1);
        quicksort_freqs(target,j + 1,last);
    }
    return target;
}

Freq** sort_rlexicographical(Freq** target,int last) 
{
    int i,j;
    Freq* temp;

    for (i = first; i < last; ++i)

        for (j = i + 1; j < last + 1; ++j) {

            if (strcmp(target[i]->word,target[j]->word) < 0) {
                temp = target[i];
                target[i] = target[j];
                target[j] = temp;
            }
        }

    debug("In lexicographical reverse order:");
    for (i = 0; i < last + 1; ++i) {
        debug("%s",target[i]->word);
    }
    debug("-----------------------");

    return target;
}

void print_reverse(Freq** target,int size) {
    for (int i = size - 1; i >= 0; i--) {
        printf("%s ",target[i]->word);
        printf("%d \n",target[i]->times);
    }
}

积分无效:

196    for (int i = 0; i < size; i++) {
197        free(words[i]);
198    }

和:

201    for (int i = 0; i < hist_size; i++) {
202        free(histogram->freqs[i]->word);
203    }

我的行动计划:

➜  tmp1 ./kontrolinis2
Please enter a number of words > 4
Enter word > test1
Enter word > test1
Enter word > test2
Enter word > test2
DEBUG kontrolinis2.c:150: Frequency table:
DEBUG kontrolinis2.c:152: test1 2
DEBUG kontrolinis2.c:152: test2 2
DEBUG kontrolinis2.c:154: -----------------------
DEBUG kontrolinis2.c:158: Sorted frequency table:
DEBUG kontrolinis2.c:160: test1 2
DEBUG kontrolinis2.c:160: test2 2
DEBUG kontrolinis2.c:162: -----------------------
DEBUG kontrolinis2.c:264: In lexicographical reverse order:
DEBUG kontrolinis2.c:266: test2
DEBUG kontrolinis2.c:266: test1
DEBUG kontrolinis2.c:268: -----------------------

Lexicographically sorted frequency table:
test1 2
test2 2

Valgrind输出(使用相同的“用户”输入):

Lexicographically sorted frequency table:
test1 2
test2 2
==9430== Invalid free() / delete / delete[] / realloc()
==9430==    at 0x4C2E14B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x1091D4: main (kontrolinis2.c:197)
==9430==  Address 0x51f19d0 is 0 bytes inside a block of size 50 free'd
==9430==    at 0x4C2E14B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x109194: main (kontrolinis2.c:192)
==9430==  Block was alloc'd at
==9430==    at 0x4C2CE5F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x108C77: main (kontrolinis2.c:89)
==9430==
==9430== Invalid free() / delete / delete[] / realloc()
==9430==    at 0x4C2E14B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x109217: main (kontrolinis2.c:202)
==9430==  Address 0x51f1ad0 is 0 bytes inside a block of size 50 free'd
==9430==    at 0x4C2E14B: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x109194: main (kontrolinis2.c:192)
==9430==  Block was alloc'd at
==9430==    at 0x4C2CE5F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x108C77: main (kontrolinis2.c:89)
==9430==
==9430==
==9430== HEAP SUMMARY:
==9430==     in use at exit: 118 bytes in 4 blocks
==9430==   total heap usage: 18 allocs,18 frees,2,612 bytes allocated
==9430==
==9430== 16 bytes in 2 blocks are definitely lost in loss record 1 of 2
==9430==    at 0x4C2CE5F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x108DC7: main (kontrolinis2.c:133)
==9430==
==9430== 102 bytes in 2 blocks are definitely lost in loss record 2 of 2
==9430==    at 0x4C2EF35: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9430==    by 0x108D23: main (kontrolinis2.c:104)
==9430==
==9430== LEAK SUMMARY:
==9430==    definitely lost: 118 bytes in 4 blocks
==9430==    indirectly lost: 0 bytes in 0 blocks
==9430==      possibly lost: 0 bytes in 0 blocks
==9430==    still reachable: 0 bytes in 0 blocks
==9430==         suppressed: 0 bytes in 0 blocks
==9430==
==9430== For counts of detected and suppressed errors,rerun with: -v
==9430== ERROR SUMMARY: 6 errors from 4 contexts (suppressed: 0 from 0)

纠正我是否应该粘贴整个程序,而不是它的主要部分,或某种工作原型.但是,这里的主要细节
是包含关键字“malloc”和“free”的行.

更新:
从库中添加两个函数,用于此处:“get_pos_num”和“get_word”:

char* get_word(char* message,char* output)
{

    while (1) {
        printf("%s",message);
        if (scanf("%s",output) == 1 && getchar() == '\n') {
            break;
        } else {
            while (getchar() != '\n')
                ;
            printf("Error: not a string,or too many arguments\n");
        }
    }

    return output;
}

int get_pos_num(char* message,int zero_allowed)
{
    int num;
    int margin;

    if (zero_allowed) {
        margin = 0;
    } else {
        margin = 1;
    }

    while (1) {
        printf("%s",message);
        if (scanf("%d",&num) == 1 && getchar() == '\n') {
            if (num >= margin) {
                break;
            } else {
                printf("Error: number is not positive");
                if (zero_allowed) {
                    printf(" or zero");
                }
                printf("\n");
            }
        } else {
            while (getchar() != '\n')
                ;
            printf("Error: not a number\n");
        }
    }

    return num;
}

解决方法

那么显而易见的问题是:
freq->word = (char*)malloc(sizeof(MAX_STRING * sizeof(char)));
freq->word = words[i];

你为freq-> word分配内存并用words [i]覆盖它.

您稍后释放了这些单词,然后将您分配的许多频率释放到直方图结构中.

如果你想复制单词[i],你应该使用

freq->word = strdup(words[i]);

要么

freq->word = malloc(strlen(words[i])+1);
strcpy(freq->word,words[i]);

还注意到你也在这里做同样的事情

duplicated[i] = words[i];

当你忘记分配的内存时,两者都会导致内存泄漏.

而另一件事(我今天似乎是科伦坡)是你的

malloc上面的sizeof(MAX_STRING * sizeof(char))应该只是MAX_STRING * sizeof(char).不确定你会得到什么结果,但它要么是4或8个字节.

c – Valgrind无效,内存泄漏的更多相关文章

  1. Html5 滚动穿透的方法

    这篇文章主要介绍了Html5 滚动穿透的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. HTML5 拖放(Drag 和 Drop)详解与实例代码

    本篇文章主要介绍了HTML5 拖放(Drag 和 Drop)详解与实例代码,具有一定的参考价值,有兴趣的可以了解一下

  3. 跨域修改iframe页面内容详解

    这篇文章主要介绍了跨域修改iframe页面内容详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  4. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  5. ios – 确定核心音频AudioBuffer中的帧数

    我正在尝试访问iPhone/iPad上的音频文件的原始数据.我有以下代码,这是我需要的路径的基本开始.但是,一旦我有了一个AudioBuffer,我就不知道该怎么做了.基本上我不知道如何判断每个缓冲区包含多少帧,因此我无法从它们中可靠地提取数据.我是处理原始音频数据的新手,所以我对如何最好地读取AudioBuffer结构的mData属性有任何建议.我在过去也没有做过很多关于void指针的事情,所以在这种情况下对它的帮助也会很棒!

  6. 使用最新的Flurry SDK和ios4重新启动应用程序

    我真的希望这对我来说只是一个愚蠢的错误.我很高兴使用Flurry但这样的事情会导致我的应用被拒绝.解决方法我写了关于这个的Flurry,他们很快回到我身边,他们会调查这个.大约一个星期后,他们回信并表示他们已经在v2.6中修复了它,现在可用了.我似乎无法重现这个问题.不是说我很棒或者什么,但我还是单枪匹马地解决了这个问题.

  7. iOS – 生成并播放无限简单的音频(正弦波)

    我正在寻找一个非常简单的iOS应用程序,它带有一个启动和停止音频信号的按钮.信号只是一个正弦波,它将在整个播放过程中检查我的模型,并相应地改变音量.我的困难与任务的不确定性有关.我理解如何构建表格,填充数据,响应按钮按下等等;然而,当谈到只是无限期地继续时,我有点卡住了!任何指针都会很棒!

  8. ios – 暂停调度队列是否会暂停其目标队列?

    我想创建两个串行队列A&B.队列B是队列A的目标.我想在B上排队一些块,并暂停它直到我准备执行它们,但是我想继续在队列A上执行块.如果我暂停B,这还会暂停它的目标队列(队列A)吗?我的想法是,我想安排这些特定的块在稍后日期执行但是我不希望它们同时运行而我不这样做想要处理信号量.但我希望队列A继续处理它的块,而B则被暂停如果不清楚这里是一些示例代码解决方法queueB被挂起,但queueA未被挂起.queueA和queueB被挂起.

  9. 为什么这个OpenGL ES 2.0着色器不能在iOS上使用我的VBO?

    如果有人能够了解这里出了什么问题,也许是对gl命令或其他一些不兼容的命令序列的错误排序,我将非常感谢你的帮助.尽管谷歌在“OpenGLES2.0编程指南”中进行了大量研究和研究,但我一直试图让这段代码整天都没有成功.我正在尝试在iPhone上的OpenGLES2.0中使用顶点缓冲区对象和自定义着色器.我试图交错来自以下类型的一系列自定义结构的顶点数据:位置,半径和颜色字节分别考虑顶点位置,点大小和

  10. ios – 使用CocoaPods post install hook将自定义路径添加到HEADER_SEARCH_PATHS

    解决方法在Podfile中定义一个方法:然后在post_install中调用该方法:

随机推荐

  1. 从C到C#的zlib(如何将byte []转换为流并将流转换为byte [])

    我的任务是使用zlib解压缩数据包(已接收),然后使用算法从数据中生成图片好消息是我在C中有代码,但任务是在C#中完成C我正在尝试使用zlib.NET,但所有演示都有该代码进行解压缩(C#)我的问题:我不想在解压缩后保存文件,因为我必须使用C代码中显示的算法.如何将byte[]数组转换为类似于C#zlib代码中的流来解压缩数据然后如何将流转换回字节数组?

  2. 为什么C标准使用不确定的变量未定义?

    垃圾价值存储在哪里,为什么目的?解决方法由于效率原因,C选择不将变量初始化为某些自动值.为了初始化这些数据,必须添加指令.以下是一个例子:产生:虽然这段代码:产生:你可以看到,一个完整的额外的指令用来移动1到x.这对于嵌入式系统来说至关重要.

  3. 如何使用命名管道从c调用WCF方法?

    更新:通过协议here,我无法弄清楚未知的信封记录.我在网上找不到任何例子.原版的:我有以下WCF服务我输出添加5行,所以我知道服务器是否处理了请求与否.我有一个.NET客户端,我曾经测试这一切,一切正常工作预期.现在我想为这个做一个非托管的C客户端.我想出了如何得到管道的名称,并写信给它.我从here下载了协议我可以写信给管道,但我看不懂.每当我尝试读取它,我得到一个ERROR_broKEN_P

  4. “这”是否保证指向C中的对象的开始?

    我想使用fwrite将一个对象写入顺序文件.班级就像当我将一个对象写入文件时.我正在游荡,我可以使用fwrite(this,sizeof(int),2,fo)写入前两个整数.问题是:这是否保证指向对象数据的开始,即使对象的最开始可能存在虚拟表.所以上面的操作是安全的.解决方法这提供了对象的地址,这不一定是第一个成员的地址.唯一的例外是所谓的标准布局类型.从C11标准:(9.2/20)Apointe

  5. c – 编译单元之间共享的全局const对象

    当我声明并初始化一个const对象时.两个cpp文件包含此标头.和当我构建解决方案时,没有链接错误,你会得到什么如果g_Const是一个非const基本类型!PrintInUnit1()和PrintInUnit2()表明在两个编译单元中有两个独立的“g_Const”具有不同的地址,为什么?

  6. 什么是C名称查找在这里? (&amp;GCC对吗?)

    为什么在第三个变体找到func,但是在实例化的时候,原始变体中不合格查找找不到func?解决方法一般规则是,任何不在模板定义上下文中的内容只能通过ADL来获取.换句话说,正常的不合格查找仅在模板定义上下文中执行.因为在定义中间语句时没有声明func,并且func不在与ns::type相关联的命名空间中,所以代码形式不正确.

  7. c – 在输出参数中使用auto

    有没有办法在这种情况下使用auto关键字:当然,不可能知道什么类型的.因此,解决方案应该是以某种方式将它们合并为一个句子.这可用吗?解决方法看起来您希望默认初始化给定函数期望作为参数的类型的对象.您无法使用auto执行此操作,但您可以编写一个特征来提取函数所需的类型,然后使用它来声明您的变量:然后你就像这样使用它:当然,只要你重载函数,这一切都会失败.

  8. 在C中说“推动一切浮动”的确定性方式

    鉴于我更喜欢将程序中的数字保留为int或任何内容,那么使用这些数字的浮点数等效的任意算术最方便的方法是什么?说,我有我想写通过将转换放在解析的运算符树叶中,无需将表达式转化为混乱是否可以使用C风格的宏?应该用新的类和重载操作符完成吗?解决方法这是一个非常复杂的表达.更好地给它一个名字:现在当您使用整数参数调用它时,由于参数的类型为double,因此使用常规的算术转换将参数转换为double用C11lambda……

  9. objective-c – 如何获取未知大小的NSArray的第一个X元素?

    在objectiveC中,我有一个NSArray,我们称之为NSArray*largeArray,我想要获得一个新的NSArray*smallArray,只有第一个x对象…

  10. c – Setprecision是混乱

    我只是想问一下setprecision,因为我有点困惑.这里是代码:其中x=以下:方程的左边是x的值.1.105=1.10应为1.111.115=1.11应为1.121.125=1.12应为1.131.135=1.14是正确的1.145=1.15也正确但如果x是:2.115=2.12是正确的2.125=2.12应为2.13所以为什么在一定的价值是正确的,但有时是错误的?请启发我谢谢解决方法没有理由期望使用浮点系统可以正确地表示您的帖子中的任何常量.因此,一旦将它们存储在一个双变量中,那么你所拥有的确切的一

返回
顶部