K&安培; R的atoi通用内存泄漏 [英] K&R atoi-general memory leak

查看:135
本文介绍了K&安培; R的atoi通用内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的K&安培; R第二版的例子来学习C和编码,因为我觉得这是做事的正确方法。总之,当我运行这个程序后编译程序会被卡住。我用编译脚本的执行的valgrind。

 的#include<&文件ctype.h GT;INT的atoi(char中[])
{
    INT I,N,标志;
    对于(i = 0; isspace为(S [I]);我++)
        ;
    签名=(S [I] ==' - ')? -1:1;
    如果(S [I] =='+'|| S [I] ==' - ')
        我++;
    对于(INT N = 0; ISDIGIT(S [I]); N ++)
        每组10 * N +(S [I] - '0');
    返回标志* N;
}诠释的main()
{
    字符输入[] =-12345
    与atoi(输入);
}
在〜/文档/项目startup001#vaibhavchauhan / K-R上的git:主X [0点43分36秒]
$的valgrind ./atoi-general
== == 8075 MEMCHECK,内存错误检测
== == 8075版权所有(C)2002 - 2015年和GNU GPL的,Julian Seward写等。
== == 8075 Valgrind的使用-3.11.0和LibVEX;与-h版权信息重新运行
== == 8075命令:./atoi-general
== == 8075
^ C == == 8075


解决方案

在你的第二个循环,你迭代 N 但是你用 I 为您计算和计算。这将导致你观察到无限循环。为了解决这个问题,使用 I 为指标一致:

  INT的atoi(char中[])
{
    INT I,签署,正;
    对于(i = 0; isspace为(S [I]);我++)
        ;
    签名=(S [I] ==' - ')? -1:1;
    如果(S [I] =='+'|| S [I] ==' - ')
        我++;
    为(N = 0; ISDIGIT(S [I]);我+ +)
        每组10 * N +(S [I] - '0');
    返回标志* N;
}

需要注意的是指数的类型应该是为size_t ,而不是 INT ,因为后者可能不够大,指数每数组。为了这个目的,类型的索引 INT 是好的,但。

I am following K&R second edition examples to learn C and coding as I think this is correct way of doing things. Anyhow when I run this program post compilation the program get stuck. I used valgrind for execution of compiled script.

#include <ctype.h>

int atoi(char s[])
{
    int i, n, sign;
    for(i = 0; isspace(s[i]); i++)
        ;
    sign = (s[i] == '-')? -1 : 1;
    if (s[i] == '+'|| s[i] == '-')
        i++;
    for (int n = 0; isdigit(s[i]); n++)
        n = 10 * n + (s[i]-'0');
    return sign * n;
}

int main()
{
    char input[] = "       -12345";
    atoi(input);
}
# vaibhavchauhan at startup001 in ~/Documents/Projects/K-R on git:master x [0:43:36]
$ valgrind ./atoi-general
==8075== Memcheck, a memory error detector
==8075== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==8075== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==8075== Command: ./atoi-general
==8075==
^C==8075==

解决方案

In your second loop, you are iterating n but you use i for your computations and computations. This leads to the infinite loop you observe. To fix this, use either i as an index consistently:

int atoi(char s[])
{
    int i, sign, n;
    for(i = 0; isspace(s[i]); i++)
        ;
    sign = (s[i] == '-')? -1 : 1;
    if (s[i] == '+'|| s[i] == '-')
        i++;
    for (n = 0; isdigit(s[i]); i++)
        n = 10 * n + (s[i]-'0');
    return sign * n;
}

Note that indices should have type size_t, not int as the latter might be not large enough to index every array. For this purpose, an index of type int is fine though.

这篇关于K&安培; R的atoi通用内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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