0

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

有人可以就这些未初始化变量的情况提供任何帮助都会有所帮助。我认为这是使用 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)
4

1 回答 1

2

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

此外,抑制文件文档:

现在,对于代码,很明显每个 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 有匹配的 free。在 add 函数中,有一个用于结果的 calloc。缺少一个免费的。在 strpadleft 中,结果函数有一个 calloc。所以它返回一个动态分配的变量,应该由调用者释放。那不见了。然而,真正的问题是 strpadleft 可能会提前返回(返回字符串)而不分配任何东西。调用者无法知道函数是否正在分配新值。这是错误的。要么通知调用者做了什么操作,要么使分配统一(总是分配)。

结论:释放内存是匹配所有分配的简单问题。您使用变量跟踪分配。当你不再需要它们时,释放它们。

于 2013-02-24T23:03:39.773 回答