在功能上抛出内存错误C的malloc [英] C malloc in function throw memory error

查看:160
本文介绍了在功能上抛出内存错误C的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我的功能。

I have a problem with my function.

char *readFnName(char *fnString, int n, int offset, int *size) {
    char *fnName;
    int nameBuffer, i, j;

    i = offset;
    j = 0;
    nameBuffer = 8;
    fnName = (char *)malloc(nameBuffer);

    while(*(fnString + i) != '(' && i<n) {
        *(fnName + j++) = *(fnString + i++);
        if (j>=nameBuffer) {
            nameBuffer += 8;
            fnName = (char *)realloc(fnName, nameBuffer);
        }
    }

    *(fnName + j++) = '\0';
    *size = j;

    return fnName;
}

我添加此功能的字符串,这是读好,但我运行一个循环此功能,并在第三次迭代此行粉碎:

I add this function a string, and this is read it well, but i run this function in a loop, and in the 3rd iteration this line crushed:

fnName = (char *)malloc(nameBuffer);

我得到在NetBeans调试器的消息:

I get a message in netbeans debugger:

malloc(): memory corruption: 0x08a62218

我使用NetBeans和lubuntu。

I use netbeans and lubuntu.

推荐答案

有与code你贴没有问题。运行时错误信息表明可能存在堆损坏早些时候的计划,该计划正在显示上升以后的调用一个 *页头功能。

There's no problem with the code you posted. The runtime error message indicates that there may be heap corruption earlier on in the program, which is being shown up by a later call to an *alloc function.

尝试运行于整个程序的valgrind,它可能会发现一些东西。如果做不到这一点,仔细检查了正在使用malloc分配的缓冲区,以确保它不会溢出它们code。您可能需要分而治之,以找出该计划的一部分有问题。

Try running valgrind on the whole program, it may find something. Failing that, check carefully over code that is using malloc'd buffers to make sure it does not overflow them. You may have to divide-and-conquer to figure out which part of the program has the problem.

这篇关于在功能上抛出内存错误C的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆