c - 我以为存在内存入侵问题,是吗?

标签 c malloc heap-memory

如下,我的代码是:

int     *text(char *str)
{
    int     *cond;
    int     *temp;
    int     cond_size;
    int     num;
    int     i;

    cond_size = -1;
    cond = malloc(sizeof(int) * 1);
    *cond = 0;
    while (*str != '\0')
    {
        if (*str == ' ')
            str++;
        num = 0;
        while (*str >= '0' && *str <= '9')
            num = num * 10 + *(str++) - '0';
        temp = cond;
        cond = malloc(sizeof(int) * (++cond_size));
        i = -1;
        while (++i < cond_size)
            cond[i] = temp[i];
        cond[i] = num;
        free(temp);
    }
    g_size = (i + 1) / 4;
    return (cond);
}

我的主要功能是:

int     *text(char *str);

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

int     g_size = 0;

int     main(void)
{
    int     *test;
    int     i;

    i = 0;
    test = text(" 4 3 2 1 1 2 2 2 4 3 2 1 1 2 2 2");
    while(i < g_size)
    {
        printf("\n%d\n", test[i]);
        i++;
    }
}

使用输入字符串 4 3 2 1 1 2 2 2 4 3 2 1 ...,将打印以下输出:

==============
|  4 3 2 1   |
|4        '1'| <==
|3         2 |  
|2         2 |
|1         2 |
|  1 2 2 2   |
==============

但是,正如我检查的那样(<==),

'1' 被打印为 '4'

它并不像我预期的那样正确。

使用 malloc 时我的代码中是否存在内存入侵或其他错误?

最佳答案

我可以看到一些问题:

  • cond_size 为 -1:

    cond_size = -1; // Here is problem
    cond = malloc(sizeof(int) * 1);
    *cond = 0;
    while (*str != '\0')
    {
        if (*str == ' ')
            str++;
        num = 0;
        while (*str >= '0' && *str <= '9')
           num = num * 10 + *(str++) - '0';
        temp = cond;
        cond = malloc(sizeof(int) * (++cond_size)); // you are trying allocate memory with size 0
        i = -1;
        while (++i < cond_size)
            cond[i] = temp[i];
        cond[i] = num; // you are writing to not allocated memory
    

    您可以找到有关 malloc 的更多信息.

  • 温度超出范围:

    temp = cond;
    cond = malloc(sizeof(int) * (++cond_size));
    i = -1;
    while (++i < cond_size)
        cond[i] = temp[i]; // temp size is cond_size-1
    

    所以你应该通过 cond_size-1 来限制循环。

请查看fixed version.

<script src="//onlinegdb.com/embed/js/SJADLQEM8?theme=dark"></script>

关于c - 我以为存在内存入侵问题,是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024376/

相关文章:

c - 函数返回类型决定

c - 从 C 中的多维数组中提取一行

C++ malloc 错误

c++ - 是否可能将 free() 与 new 和 delete 与 malloc() 一起使用?

c - 为什么下面的代码容易受到堆溢出攻击

assembly - 堆、堆栈和数据段是否在同一个汇编程序中?

c - 管道无法通过 pthread_t 工作

c - printf相关查询

c - malloc 之后 typedef 的大小没有改变

c - malloc() 中的双倍大小