memory leaks

Is it safe to say that whenever you use malloc, you should use free?

Take example below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void sendCmd(unsigned char *ans)
{
   u8 *ask;
   u8 work[5];
 

   int i;
   for(i=0;i<5;i++)
   {
     work[i] = ans[i];
   }

   ask = (u8*)malloc(sizeof(cmd));
   memcpy(ask, cmd, sizeof(cmd));
   memcpy(ask+6, work, 5);

   transmit(ask, sizeof(cmd));
}


if free() is never called on ask, will that result in a memory leak?
Yes. Unless you have a garbage collector (which you almost definitely don't), you should always free what you allocate to the heap.
unless you're using c++ where you should use new and delete
new[n] and delete[] for arrays.
closed account (N36fSL3A)
johnmerlino wrote:
Is it safe to say that whenever you use malloc, you should use free?
I'd probably say that it's pretty much required if you don't want a memory-leaky(is that a word? lol) program. You should also check if malloc fails, if it does it can crash your program when you try to access non-allocated memory.
Last edited on
Topic archived. No new replies allowed.