c - 动态内存分配 - realloc() : invalid next size

标签 c pointers malloc realloc

<分区>

我的要求是为我正在创建的 char * 变量进行动态内存分配,以便当我的应用程序中的 while 循环读取数据时,内存分配应该相应地增加,但是当我运行代码时会发生什么,我得到了错误,

*** 检测到 glibc *** ./rpp: realloc(): invalid next size: 0x0000000001376010 ***

我通过谷歌搜索 ( https://www.google.com/search?client=ubuntu&channel=fs&q=realloc%28%29%3A+invalid+next+size%3A+0x0000000002401010+&ie=utf-8&oe=utf-8#channel=fs&q=realloc%28%29:+invalid+next+size:+ ) 在 stackoverflow 中发现了很多关于这个主题的问题,但没有帮助。如果你们的专家能帮助我解决这个错误,我真的很感激,因为我现在对如何解决这个问题一无所知。在 id 之后给出错误的函数。

int execScanNetowrk(){

    FILE *fp;
    int status;
    char path[1035];
    char *pathFull;
    pathFull = (char*)malloc(sizeof(path));


    /* Open the command for reading. */
    fp = popen("nmap -sP -oG - 192.168.1.0/24", "r");

    if (fp == NULL) {
            printf("Failed to run command\n" );
            exit;
    }

    /* Read the output a line at a time - output it. path stores each line of data per iteration*/
    while (fgets(path, sizeof(path)-1, fp) != NULL) {

        pathFull = (char*)realloc(pathFull, sizeof(path));//increase memory allocation
        strcat(pathFull,path);//concatenate char * with the read data           

    }

    printf("%s\n", a);  
    /* close */
    pclose(fp);
    free(a);
    return 0;

}

非常感谢:)

最佳答案

解决此类问题的一般技术是应用 valgrind 这将为您提供更详细的错误消息,直指问题。

您的具体问题在这里:

    pathFull = (char*)realloc(pathFull, sizeof(path));//increase memory allocation

realloc 的第二个参数是您想要的总字节数不是要增加分配的字节数。您需要跟踪 pathFull 的当前大小并做 realloc(pathFull, oldSize + sizeof(path))或类似的。

您真的想在处理之前将整个 nmap 输出读入内存,还是您的实际目标是在处理它们之前将整个 读入内存?你的代码试图做前者,但你可能打算做后者,在这种情况下 getline 可能比使用 fgets 更容易使用.

强制吹毛求疵:在用 C 编写代码时不要强制转换 malloc 的返回值也不realloc .这是不必要的,并且可能会在您忘记 #include <stdlib.h> 时阻止编译器注意到.

关于c - 动态内存分配 - realloc() : invalid next size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884869/

相关文章:

c - 合并排序期间的运行时错误

c - 需要关于在 C 中实现 malloc 和 free 的建议

c - sizeof char 指针和指向指针的指针

c - 初始化器不是常量。马洛克

c - 为什么以下代码会产生段错误?

c - 传递给另一个函数时局部变量的数据损坏

c++ - 为什么 CRC 和 C++ 代码版本的 CRC 计算不同?

c - 理解 C 中的 pthread_create 参数

c - Trie树并找到出现次数最多的n个单词,指针

c++ - static_cast const 引用 void*