【问题标题】:I thought there is a memory intrusion problem, is that right?我以为是内存入侵问题,是这样吗?
【发布时间】:2020-05-18 07:58:45
【问题描述】:

如下,我的代码是:

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 时是否存在内存入侵或其他错误?

【问题讨论】:

  • 您的代码中有一些奇怪的东西:例如,为什么在存储分配的堆区域 malloc 的地址之后立即有*cond = 0 行?第一个 malloc 的内存将丢失。此外,您可能需要考虑检查 malloc 的 retun 值并使用 realloc 而不是自己做。

标签: c malloc heap-memory


【解决方案1】:

我可以看到一些问题:

  • 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.

&lt;script src="//onlinegdb.com/embed/js/SJADLQEM8?theme=dark"&gt;&lt;/script&gt;

【讨论】:

  • @stonesteel 希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-13
  • 2018-05-04
  • 2010-10-31
  • 2012-07-17
  • 2023-03-23
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多