C内存错误

时间:2013-02-24 21:23:56

标签: c valgrind calloc

我必须将数字表示为字符串并对它们执行加法运算。这是作业,我到目前为止所做的工作。它输出正确的输出,但我的程序也需要没有内存错误,当然不是那样。

有人可以提供任何有关这些未初始化变量的帮助会有所帮助。我认为这是使用malloc而不是calloc,但我也改变了它,但仍然没有骰子。

这是我的输出:

./a.out
strlen: 12
Old: 12122334455
New: 012122334455
Result: 167244668910

这是我的代码:     / *      *文件:strmath.c      * /

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>

int cmp(char *, char *, int);
void add(char *, char *, int);
char * reverse(char *);
void strReverse(char *);
char *strpadleft(char * , char,  int );

int main()
{
  char str1[] = "155122334455",
       str2[] = "12122334455"; //malloc(10);
  int len = strlen(str1) < strlen(str2)?strlen(str2):strlen(str1);
  printf("strlen: %d\n", len);
  // int result = cmp(str1, str2, len);
  // if(result > 0)
  //   printf("%s > %s\n", str1, str2);
  // else if(result < 0)
  //   printf("%s > %s\n", str2, str1);
  // else
  //   printf("%s == %s\n", str1, str2);

    add(str1, str2, len);
    return 0; 
}

int cmp(char *str1, char *str2, int longest) {
    if (strlen(str1) < strlen(str2))
        return -1;
    else if (strlen(str1) > strlen(str2))
        return 1;
    else
        return strncmp(str1, str2, longest);
}

void add(char *str1, char *str2, int longest) {

    char * num1 = strpadleft(str1, '0', longest);
    char * num2 = strpadleft(str2, '0', longest);
    strReverse(num1);
    strReverse(num2);

    char * result = calloc(longest + 2  , sizeof(char));
    int i, x, carry=0;
    for (i = 0; i < longest;i++) {
        x = (num1[i] - '0') + (num2[i] - '0') + carry;

        if (x >= 10) {
            carry = 1;
            x -= 10;
        }
        else {
            carry = 0;
        }
        result[i] = x + '0';
    }

    if (carry == 1) { result[i+1] = '1';}
    strReverse(result);
    printf("Result: %s\n", result );
    //free(result);
    //free(num1);
    //free(num2);
}

char *strpadleft(char * string, char pad, int padSize)
{
    int ssize = strlen(string);
    if (padSize <= ssize) return string;

    char *padded = calloc((padSize + 1) , sizeof(char));
    memset(padded, pad, padSize-ssize);
    padded = strcat(padded, string);
    printf("Old: %s\nNew: %s\n", string, padded);
    return padded;
}

void strReverse(char* str){
    int length = strlen(str);
    char temp;
    int i,j;
    for(i = 0, j = length-1;i < (length-1)/2; i++, j--){
        temp = str[i];
        str[i]=str[j];
        str[j] = temp;
    }
    return;
}

这是我的valgrind输出(valgrind的完整输出是http://textsnip.com/ae3c9a,因为它对于SO来说太多了):

==17115== Memcheck, a memory error detector
==17115== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==17115== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==17115== Command: a.out
==17115== 
==17115== Conditional jump or move depends on uninitialised value(s)
==17115==    at 0x414F76: __linkin_atfork (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x404383: ptmalloc_init.part.8 (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x407E64: malloc_hook_ini (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x4538E2: _dl_init_paths (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x415788: _dl_non_dynamic_init (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x416002: __libc_init_first (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x40173C: (below main) (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==  Uninitialised value was created
==17115==    at 0x45018A: brk (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x41370B: sbrk (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x401C95: __pthread_initialize_minimal (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x4016F0: (below main) (in /p2/hj/jsiegal/csc352/assg5/a.out)

...

==17115== Use of uninitialised value of size 8
==17115==    at 0x405B27: _int_malloc (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x408E29: calloc (in /p2/hj/jsiegal/csc352/assg5/a.out)
==17115==    by 0x401418: add (strmath.c:51)
==17115==    by 0x4012AB: main (strmath.c:31)
==17115==  Uninitialised value was created by a stack allocation
==17115==    at 0x453ADD: _dl_init_paths (in /p2/hj/jsiegal/csc352/assg5/a.out)

固定

/*
 * File: strmath.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <ctype.h>

int cmp(char *, char *, int);
void add(char *, char *, int);
char * reverse(char *);
void strReverse(char *);
void strpadleft(char * , char *, char,  int );

int main()
{
  char str1[] = "155122334455",
       str2[] = "12122334455"; //malloc(10);
  int len = strlen(str1) < strlen(str2)?strlen(str2):strlen(str1);
  printf("strlen: %d\n", len);
  // int result = cmp(str1, str2, len);
  // if(result > 0)
  //   printf("%s > %s\n", str1, str2);
  // else if(result < 0)
  //   printf("%s > %s\n", str2, str1);
  // else
  //   printf("%s == %s\n", str1, str2);

    add(str1, str2, len);
    return 0; 
}

int cmp(char *str1, char *str2, int longest) {
    if (strlen(str1) < strlen(str2))
        return -1;
    else if (strlen(str1) > strlen(str2))
        return 1;
    else
        return strncmp(str1, str2, longest);
}

void add(char *str1, char *str2, int longest) {

    char * num1 = malloc((longest + 1) * sizeof(char));
    memset(num1, '\0', longest+1);        
    strpadleft(str1, num1, '0', longest);

    char * num2 = malloc((longest + 1) * sizeof(char));
    memset(num2, '\0', longest+1);
    strpadleft(str2, num2, '0', longest);

    strReverse(num1);
    strReverse(num2);

    char * result = malloc(longest + 2  * sizeof(char));
    memset(result, '\0', longest+2);
    int i, x, carry=0;
    for (i = 0; i < longest;i++) {
        x = (num1[i] - '0') + (num2[i] - '0') + carry;

        if (x >= 10) {
            carry = 1;
            x -= 10;
        }
        else {
            carry = 0;
        }
        result[i] = x + '0';
    }

    if (carry == 1) { result[i+1] = '1';}
    strReverse(result);
    printf("Result: %s\n", result );
    free(result);
    free(num1);
    free(num2);
}

void strpadleft(char * string, char *padded, char pad, int padSize)
{
    int ssize = strlen(string);
    if (padSize <= ssize) {
        strcpy(padded, string);
        return;
    }

    //char *padded = malloc((padSize + 1) * sizeof(char));
    //memset(padded, '\0', padSize);
    memset(padded, pad, padSize-ssize);
    padded = strcat(padded, string);
    printf("Old: %s\nNew: %s\n", string, padded);
    return;
}

void strReverse(char* str){
    int length = strlen(str);
    char temp;
    int i,j;
    for(i = 0, j = length-1;i < (length-1)/2; i++, j--){
        temp = str[i];
        str[i]=str[j];
        str[j] = temp;
    }
    return;
}

valgrind输出:

==12778== Memcheck, a memory error detector
==12778== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==12778== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==12778== Command: a.out
==12778==
strlen: 12
Old: 12122334455
New: 012122334455
Result: 167244668910
==12778==
==12778== HEAP SUMMARY:
==12778==     in use at exit: 0 bytes in 0 blocks
==12778==   total heap usage: 3 allocs, 3 frees, 40 bytes allocated
==12778==
==12778== All heap blocks were freed -- no leaks are possible
==12778==
==12778== For counts of detected and suppressed errors, rerun with: -v
==12778== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

1 个答案:

答案 0 :(得分:2)

valgrind日志不代表您的程序执行。它实际上对libc内部函数很疯狂。显而易见的原因是,您正在使用的精确libc版本缺少正确的抑制文件(误报内存访问/分配错误列表)。 Valgrind应该自动解决,但这并没有发生。您需要在系统中重新编译valgrind,以便它再次检测到正确的libc,或者它完全无法自动检测它(然后您需要手动构建一个suppresion文件)。例如,见:

此外,抑制文件文档:

现在,对于代码,很明显每个calloc都没有相应的free。我将复制粘贴我的valgrind执行,以便了解真正的valgrind输出:

(...)
==26074== 13 bytes in 1 blocks are definitely lost in loss record 1 of 2
==26074==    at 0x4C29E46: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==26074==    by 0x400A15: strpadleft (in /tmp/a)
==26074==    by 0x40081A: add (in /tmp/a)
==26074==    by 0x4007D4: main (in /tmp/a)
==26074== 
==26074== 14 bytes in 1 blocks are definitely lost in loss record 2 of 2
==26074==    at 0x4C29E46: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==26074==    by 0x40084B: add (in /tmp/a)
==26074==    by 0x4007D4: main (in /tmp/a)

这显示了正在发生的事情:没有calloc匹配免费。在add函数中,有一个结果的calloc。免费缺席。在strpadleft中,有一个结果函数的calloc。因此它返回一个dinamically分配的变量,该变量应由调用者释放。那是不见了。然而,真正的问题是strpadleft可能会提前返回(返回字符串)而不分配任何东西。调用者无法知道函数是否正在分配新值。这是错的。通知调用者完成的操作是什么,或者使分配统一(总是分配)。

结论:释放内存是匹配所有分配的简单问题。您可以跟踪变量的分配情况。如果你不再需要它们,请释放它们。