0

I have a function like

char *mdb_data = NULL;
int mdb_dataLen = 0;

char *getMDBDataPtr(int len)
{
    if(len <= 0)
        return NULL;

    if(mdb_data == NULL)
    {
        mdb_data = (char *)malloc(len);
        memset(mdb_data, 0, len);
        mdb_dataLen = len;
    }
    else
    {
        if(mdb_dataLen < len)
        {
            free(mdb_data);
            mdb_data=NULL;
            mdb_data = (char *)malloc(len);
            memset(mdb_data, 0, len);
            mdb_dataLen = len;
        }
    }
    return mdb_data;
}

When this function is called once i.e mdb_data=NULL it works. Afterwards when I called it with length 1 , 2 , 3 it failed when freeing memory for 3rd case i.e it free works fine twice and the crashes the application. Any ideas why this might be happening ?

pburka
  • 1,434
  • 9
  • 12
Saad Hussain
  • 63
  • 1
  • 9
  • The posted looks fine. Do you modify `mdb_data` in the caller by any chance? – P.P Sep 29 '13 at 20:59
  • 3
    [Do not cast the return value of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). –  Sep 29 '13 at 21:03
  • I am using it for receiving data over sockets – Saad Hussain Sep 29 '13 at 21:04
  • 1
    Possibly a buffer overrun somewhere else is trashing the memory. Please show the code that uses this function. – paddy Sep 29 '13 at 21:07
  • Nit: I would make the function not return anything (caller uses mdb_data directly), or take in a char** to modify so as to be explicit that a particular pointer is being mucked with. Likely unrelated to the actual problem at hand, though :) In any case, could malloc be *retuning NULL* for some reason such as an excessive len? – user2246674 Sep 29 '13 at 21:08
  • 1
    I suggest you use `realloc` rather than `free` and `malloc`. The implementation might be able to detect that the new allocation can use the same space as the old one because of padding. – Barmar Sep 29 '13 at 21:15
  • @Barmar realloc doesnt work issue still exists – Saad Hussain Sep 29 '13 at 21:22
  • When your function returns newly allocate memory you're careful to `memset` it to 0. (Tip: `calloc` does that for you.) But when you return the existing buffer you don't zero it. If your caller is expecting the buffer to be clear, this may be contributing to your problems. – pburka Sep 29 '13 at 21:23
  • I didn't intend that realloc would solve the problem (that's why I put it in a comment, not an answer), just that it's a better way to do what you're doing. – Barmar Sep 29 '13 at 21:24
  • Can the argument (`len`) ever be < 0 ? – wildplasser Sep 29 '13 at 23:23
  • I got the problem.One of the procedures in my code was overflowing the buffer.Thank you guys anyway for the tips – Saad Hussain Oct 01 '13 at 12:56

0 Answers0