Click here to Skip to main content
16,020,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
int foo(int in) 
{
  int *buf1 = (int *)malloc(1000*sizeof(int));
  if(!buf1) return -1;
  int *buf2 = (int *)malloc(2000*sizeof(int));
  if(!buf2) return -1;

  int retVal = process(in,buf1,buf2);

  free(buf1);
  free(buf2);

  return retVal;
}


What I have tried:

I am not able to find any bug, please suggest if any is there?
Posted
Updated 13-May-18 7:21am
v2

The code is almost fine: you have a memory leak if malloc fails for buf2 (in such a case buf1 memory is not released).
 
Share this answer
 
At first glance, there is a potential memory leak. When buf2 allocation fails you don't care about previous one (buf1) and you immediately return from function without freeing buf1. You should take care of buf1.

Eg.:
C++
if (!buf2) {
    free(buf1);

    return -1;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900