Valgrind和strlen()函数错误

时间:2015-01-24 11:15:39

标签: c memory-leaks valgrind

我有一些考试计划。考试系统与valgrind合作。

请帮帮我 我在valgrind中有一些错误,我不知道,如何在我的程序中解决它的错误: 我想将stdin复制到指针中的*并从stdin中删除所有空格和换行符

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

#define DELTA 2
unsigned int my_strlen(char *str);
char *get_expression(void);
int main(void)
{
    char *in, *out;
    in = get_expression();
    if (!in) {
        return 1;
    }
    out = calloc(my_strlen(in), 1);
    free(out);
    free(in);
    return 0;
}
char *get_expression(void)
{
    char *in, *in_bckp, t;
    in = malloc(DELTA);
    if (!in) {
        return NULL;
    }
    int i, c;
    for (i = 0, c = DELTA; (t = getchar()) != EOF; i++) {
        if (i >= c) {
            in_bckp = in;
            in = realloc(in, c + DELTA);
            if (!in) {
                free(in_bckp);
                return NULL;
            }
            c += DELTA;
        }
        if (c == ' ' || c == '\n') { // i need to remove all of the spaces or newlines
            continue;
        }
        in[i] = t;
    }
    if (i >= c) {
        in_bckp = in;
        in = realloc(in, c + DELTA);
        if (!in) {
            free(in_bckp);
            return NULL;
        }
    }
    in[i] = '\0';
    return in;
}

unsigned int my_strlen(char *str)
{
    unsigned int i;
    for (i = 0; str[i] != '\0' && i < 40000; i++);
    return i;
}

和我在valgrind的错误:

ivr@debian:/tmp
$ valgrind --leak-check=full --track-origins=yes ./a.out < ~/work/programming/kursovik/parsing/test/data
==5044== Memcheck, a memory error detector
==5044== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==5044== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==5044== Command: ./a.out
==5044== 
==5044== Conditional jump or move depends on uninitialised value(s)
==5044==    at 0x4007D5: my_strlen (test.c:59)
==5044==    by 0x400666: main (test.c:16)
==5044== 
==5044== 
==5044== HEAP SUMMARY:
==5044==     in use at exit: 0 bytes in 0 blocks
==5044==   total heap usage: 17 allocs, 17 frees, 280 bytes allocated
==5044== 
==5044== All heap blocks were freed -- no leaks are possible
==5044== 
==5044== For counts of detected and suppressed errors, rerun with: -v
==5044== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

请帮我解决这个错误。

1 个答案:

答案 0 :(得分:2)

您在in数组中留下了空白。基本上,你说:

int i, t;

for (i = 0; (t = getchar()) != EOF; i++) {
    if (t == ' ' || t == '\n') continue;
    in[i] = t;
}

当您阅读空格或换行符时,您会跳过作业,但会增加i++。 Valgrind(正确地)将in中的这些差距视为单元化内存。

for循环不是一个好选择。 while循环可能更好:

int t;
int i = 0;

while ((t = getchar()) != EOF) {
    if (t != ' ' && t != '\n') in[i++] = t;
}

请注意,只有在发生赋值时,计数器i才会递增。这两个密切相关的事件几乎同时进行。