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 8440275
In Process

The Archive Base Latest Questions

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

When trying to reallocate memory I crash when using this code: //value of i

  • 0

When trying to reallocate memory I crash when using this code:

//value of i is currently 4096
while((c = recv(sock, htmlbff + q, MAXDATASIZE, 0)) > 0)
{
    if((i - q) < MAXDATASIZE)
    {
            i *= 2;
            if(!(tmp = realloc(htmlbff, i)))
            {
                free(htmlbff);
                printf("\nError! Memory allocation failed!");
                return 0x00;
            }
            htmlbff = tmp;
    }
    q += c;
}

it crashes because of a memory leak…. HOWEVER the following code does not crash:

while((c = recv(sock, htmlbff + q, MAXDATASIZE, 0)) > 0)
{
    if((i - q) < MAXDATASIZE)
    {
        i *= 2;
        if(!(tmp = realloc(htmlbff, i)))
        {
            free(htmlbff);
            printf("\nError! Memory allocation failed!");
            return 0x00;
        }
    }
    htmlbff = tmp;
    q += c;
}

How can moving htmlbff = tmp; outside of the if statement be fixing this problem? It doesn’t seem to set htmlbff to tmp when inside the if statement… I am extremely confused.

  • 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-10T08:14:53+00:00Added an answer on June 10, 2026 at 8:14 am
    /*
     * I assume these exist, and more or less fit the requirements described.
     * They don't have to be these specific numbers, but they do need to have
     * the specified relationships in order for the code to work properly.
     */
    #define MAXDATASIZE 4096    /* any number here is ok, subject to rules below */
    int i = 4096;               // i >= MAXDATASIZE, or the first recv can trigger UB
    char *htmlbff = malloc(i);  // ITYK you can't realloc memory that wasn't malloc'd
    int q = 0;                  // q <= i-MAXDATASIZE
    
    /* maybe other code */
    
    while((c = recv(sock, htmlbff + q, MAXDATASIZE, 0)) > 0)
    {
        /*
         * You've already just read up to MAXDATASIZE bytes.
         * if (i-q) < MAXDATASIZE, then **your buffer is already too small**
         * and that last `recv` may have overrun it.
         */
        if((i - q) < MAXDATASIZE)
        {
            ... reallocate htmlbff ...
        }
        /* Then you bump q...but too late.  lemme explain in a sec */
        q += c;
    }
    

    Let’s say you recv 4096 bytes twice in a row. What happens is:

    1. The first read reads 4096 bytes, starting at htmlbff + 0.
    2. Since q is still 0, i - q == 4096, so no allocation is done.
    3. q is bumped up by 4096.
    4. The second read gets 4096 bytes, starting at htmlbff + 4096. But wait, since we didn’t resize it last iteration, htmlbff is only 4096 bytes big, and the entire read spills out of the buffer!
    5. If you’re lucky, the overrun causes a segfault and the program dies. If you’re not, then the CPU just soldiers on, and any behavior from here on is undefined. There’s very little point in even diagnosing further issues at this point, since $DEITY knows what the code just trashed.

    Try this instead…

    while((c = recv(sock, htmlbff + q, MAXDATASIZE, 0)) > 0)
    {
        /* **First**, bump `q` past the stuff you just read */
        q += c;
    
        /*
         * **Now** check the buffer.  If i-q is too small at this point, the buffer is
         * legitimately too small for the next read, and also hasn't been overrun yet.
         */
        if((i - q) < MAXDATASIZE)
        {
            /* This temp pointer **really** should be limited in scope */
            char *double_sized;
    
            /* Note that otherwise, i'm using the "broken" resize code.
             * It should work fine.
             */
            i *= 2;
            if(!(double_sized = realloc(htmlbff, i)))
            {
                free(htmlbff);
                printf("\nError! Memory allocation failed!");
                return 0x00;
            }
            htmlbff = double_sized;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying reallocate more 256 bytes to buffer on each loop call. In this
I am trying to dynamically reallocate memory for an array of structs (actually an
I'm currently writing a linked list and trying to free up memory allocations when
I got really stuck trying to deallocate memory using delete without it being in
I'm trying to free memory that's reallocated but I get an error... float *
Trying to make this jQuery filter that uses .find case-insensitive. For example, when the
Trying to figure out how I can do this properly. The print_r looks like
trying to figure out why this is happening - I have an input text
I've been trying to figure this out for hours now, and I'm at my
I am trying to loop through a table using a cursor: DEClARE @ProjectOID as

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.