gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:06:18 24 4
gpt4 key购买 nike

如下,我的代码是:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com