-4

I came across this in an assessment and I need to find the bug and explain why.

int process(int, int*, int*); 

int example10(int in) 
{
    int *buffer1 = (int*)malloc(1000 * sizeof(int));
    if (!buffer1)
        return -1;

    int *buffer2 = (int*)malloc(2000 * sizeof(int));
    if (!buffer2)
        return -1;

    int retVal = process(in, buffer1, buffer2);

    free(buffer1);
    free(buffer2);

    return retVal;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
JJII
  • 3
  • 2

3 Answers3

1

If the second malloc fails you return from the function and don't free the memory from the first malloc call.

if (!buffer2)
{
    //free( buffer1 ) ;
    return -1;
}
2501
  • 25,460
  • 4
  • 47
  • 87
  • @JJII Please take the time to format your question correctly. If any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. – 2501 Oct 29 '14 at 18:17
  • Will do I need 7 more minutes for that :) – JJII Oct 29 '14 at 18:19
1

It is the memory leak in case of failure in second call to malloc: you don't call free on buffer1 then. Also the first line is incorrect directive for preprocessor, however we don't know if this is deliberately malformed or is it just your urgency.

4pie0
  • 29,204
  • 9
  • 82
  • 118
1

You are freeing buffer1 and buffer2 only when both if condition got passed. What if first if condition got passed and second if condition got failed. There will be memory leak in that case. Therefore free the buffer1 in second if statement.

Amit Sharma
  • 1,987
  • 2
  • 18
  • 29