C语言 使用动态内存分配进行二进制添加



很长一段时间后,我在 C 中玩动态内存分配,遇到了一些内存泄漏问题......我只是看不出问题可能在哪里。有人可以帮忙吗?

编辑2:该程序现在即使数量非常大也能正常工作,并且:)我决定更改程序结构并使用结构而不仅仅是字符字符串。不应该有任何内存泄漏(用valgrind测试)。

当前代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct binary{
    char * number;
    size_t length;
}Tbinary;
//exterminate leading zeros
size_t exterminate(char * bin, size_t length){
char * pch = NULL;
long position = 0;
pch = strchr(bin, '1');
if(pch==NULL){
    bin[1] = '';
    length = 2;
}
else{
    position = pch-bin;
    strcpy(bin, pch);
}
return (length-position);
}
int binaryAdd(Tbinary first, Tbinary second){
int a=0, b=0, sum=0, carry=0;
size_t index = first.length;
first.number[first.length] = '';
while((first.length != 0) || (carry != 0)){
    if(first.length>1) a= first.number[first.length-2]-'0';
    else a = 0;
    if(second.length>1) b= second.number[second.length-2]-'0';
    else b = 0;
    sum = (a+b+carry)%2;
    first.number[first.length-1] = (sum)+'0';
    carry = (a+b+carry)/2;
    if(first.length >0)first.length--;
    if(second.length >0)second.length--;
}
exterminate(first.number,index);
printf("Sum: %sn", first.number);
return EXIT_SUCCESS;
}
int get_number(Tbinary *bin_addr){
char * tmp, * bin;
char ch=1;
int size = 1, index = 0;
bin = bin_addr->number;
while(ch){
    ch = getc(stdin);
    if((ch == 'n') || (ch == ' ')) ch = '';
    if((ch-'0' != 0) && (ch-'0' != 1) && (ch != '')) return EXIT_FAILURE;
    if (size-1 <=index){
        size += 5;
        tmp = (char *)realloc(bin, size*sizeof(char));
        if(tmp == NULL){
            return EXIT_FAILURE;
        }
        bin = tmp;
        bin_addr->number = bin;
    }
    bin[index++] = ch;
}
bin_addr->length = index;
bin_addr->length = exterminate(bin_addr->number, bin_addr->length);
return EXIT_SUCCESS;
} 
int main (void)
{
Tbinary bin1 = {bin1.number = NULL, bin1.length = 0};
Tbinary bin2 = {bin2.number = NULL, bin2.length = 0};
//allocate space for first number
bin1.number = (char *)malloc(sizeof(char));
if(bin1.number == NULL)
    return EXIT_FAILURE;
//allocate space for second number
bin2.number = (char *)malloc(sizeof(char));
if(bin2.number == NULL){
    free(bin1.number);
    return EXIT_FAILURE;
}
printf("Enter two binary numbers:n");
//number1 load
if(get_number(&bin1) != EXIT_SUCCESS){
    free(bin1.number);
    free(bin2.number);
    printf("Invalid input.n");
    return EXIT_FAILURE;
}
//number2 load
if(get_number(&bin2) != EXIT_SUCCESS){
    free(bin1.number);
    free(bin2.number);
    printf("Invalid input.n");
    return EXIT_FAILURE;
}
//add the two numbers
if(bin1.length >= bin2.length){
    if(binaryAdd(bin1, bin2) != EXIT_SUCCESS){
        free(bin1.number);
        free(bin2.number);
        printf("Invalid input.n");
        return EXIT_FAILURE;
    }
}
else{
    if(binaryAdd(bin2, bin1) != EXIT_SUCCESS){
        free(bin1.number);
        free(bin2.number);
        printf("Invalid input.n");
        return EXIT_FAILURE;
    }
}
free(bin1.number);
free(bin2.number);
return EXIT_SUCCESS;
}

在 binaryAdd() 中,在所有情况下,您都应该在 realloc() 之后释放总和,而不仅仅是在 realloc() 返回 null 时。在 get_number() 中也是如此。关于a = (int)strlen(first);为什么要将 strlen() 的返回转换为 int?另外,不要强制转换分配函数的返回。

您在sizeindex关系中有一个断断续续的错误:

    if (size <=index){
        size += 5;
        tmp = (char *)realloc(sum, size*sizeof(char));
        if(tmp == NULL){
            free(sum);  // free memory to avoid leak
            return EXIT_FAILURE;
        }
        sum = tmp;
    }
    for(int i=index; i>0; i--){
        sum[i] = sum[i-1];
    }
    sum[0] = num%2+'0';
    carry = num/2;
    index++;
}
sum[index] = '';

如果在进入最后一次迭代时index == size-1 ,则在分配的内存之外写入。有时这可能是无害的,对于其他人,您可能会覆盖一些重要数据而不会立即崩溃,有时它可能会导致立即崩溃(通常,当越界访问跨越页面边界时)。将测试更改为size - 1 <= index

get_number 中,如果需要realloc,则只需将char*的本地副本更改为输入缓冲区,因此如果位置更改,main中的指针将指向无效内存。它应该是

int get_number(char **bin_addr){
    char * tmp, bin = *bin_addr;
    char ch=1;
    size_t size = 1, index = 0;
    while(ch){
        ch = getc(stdin);
        if((ch == 'n') || (ch == ' ')){
            ch = '';
        }
        if((ch-'0' != 0) && (ch-'0' != 1) && (ch != '')){
            return EXIT_FAILURE;
        }
        if (size-1 <=index){
            size += 5;
            tmp = (char *)realloc(bin, size*sizeof(char));
            if(tmp == NULL){
                return EXIT_FAILURE;
            }
            bin = tmp;
            *bin_addr = bin;  // let the pointer always point to the real block
        }
        bin[index++] = ch;
    }
    return EXIT_SUCCESS;
}

并在main中被称为get_number(&bin1);.

相关内容

  • 没有找到相关文章

最新更新