Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8826603
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T07:10:46+00:00 2026-06-14T07:10:46+00:00

After a long time I’m playing with dynamic memory allocation in C and I’m

  • 0

After a long time I’m playing with dynamic memory allocation in C and I’m encountering some issues with memory leaks … I just can’t see where the problem might be. Can Anyone help please?

EDIT2:
The program now works fine even with very large numbers and is quite quick 🙂 I decided to change the program structure and used struct instead of just char string. There should not be any memory leaks (tested with valgrind).

Current code:

#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] = '\0';
    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] = '\0';

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: %s\n", 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 = '\0';

    if((ch-'0' != 0) && (ch-'0' != 1) && (ch != '\0')) 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;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T07:10:47+00:00Added an answer on June 14, 2026 at 7:10 am

    You have an off-by-one error in your size and index relationship:

        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] = '\0';
    

    If, on entering the last iteration, index == size-1, you are writing outside the allocated memory. Sometimes that can be harmless, for others you may overwrite some important data without causing an immediate crash, and sometimes it can cause an immediate crash (when the out-of-bounds access crosses a page boundary, usually). Change the test to size - 1 <= index.

    In get_number, if you need to realloc, you only change the local copy of the char* to the input buffer, so if the location changes, the pointer in main points to invalid memory. It should be

    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 = '\0';
            }
    
            if((ch-'0' != 0) && (ch-'0' != 1) && (ch != '\0')){
                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;
    }
    

    and be called get_number(&bin1); in main.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

after long time of reading on google I still don't know how can I
After a long time learning python I finally managed to make some breakthroughs: I'm
After a long time of C-style procedural coding, I am just beginning to 'get'
After a long time searching and trying I'm asking now for help: My situation:
After searching a long time for a performance bug, I read about denormal floating
I've been using Symfony for a long time but I'm new to Symfony2. After
After a long search I'm still confused about it although I found some related
I am working after a long time in grid and facing an issue. In
I heard the word buffer after a long time today and wondering if somebody
I'm trying to edit my MySQL database after a long time of taking a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.