This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

help me with heap allocation

Hi dears,
Why this piece of code does not free the heap memory fully! I tried it but after about 10 times of calling function data_readout(1) the heap gets full.
heap is 300 bytes.

 void data_readout(int line)
 {
   char *Data;

         switch (line)
         {
                 case 1:Data=dataline1();  //Data is a pointer to a char array in heap
                         break;
                 case 2:Data=dataline2();
                         break;
                 case 3:
                         break;
         }
//some code
//...
//...
//some code
                free(Data);
 }

static char *dataset_i(char *OBIS,int Value, char *Unit)
 {
         char *data,*data1;

         sprintf(data,"%s(%u%s)",OBIS,Value,Unit);
         data1=calloc(strlen(data),1);
         strcpy(data1,data);//
         return data1;
 }
 static char *dataline1()
 {
         char *r;
         char *q;
         char *c1=dataset_i(OBIS_Serialnr,EEPROM_read_int(ad_Serialnr),"");
         char *c2=dataset_i(OBIS_Bodynr,EEPROM_read_int(ad_Bodynr),"");
         char *c3=dataset_i(OBIS_Pumpont,EEPROM_read_int(ad_Pumpont),"*hours");

         strcpy(q,c1);
         strcat(q,c2);
         strcat(q,c3);
         free(c1);free(c2);free(c3);
         r=calloc(strlen(q),1);
         strcpy(r,q);//
         return r;
 }

Parents
  • Remember strings have a trailing NUL that must be allocated, and not counted with strlen()

    Make sure not to repeatedly free() the same allocation, manage the pointer so you mark is a NULL and only free() non-NULL pointers.

    Where do you allocate the q pointer?

    Wrap the calloc/free functions an track the usage, make sure you don't have a leak, and you don't multiply free, or trash the memory arena.

    Check also the heap chain, make sure you don't have an issue with fragmentation.

    Your code is sufficiently broken as presented that it needs fixing before further assessment would be useful.

Reply
  • Remember strings have a trailing NUL that must be allocated, and not counted with strlen()

    Make sure not to repeatedly free() the same allocation, manage the pointer so you mark is a NULL and only free() non-NULL pointers.

    Where do you allocate the q pointer?

    Wrap the calloc/free functions an track the usage, make sure you don't have a leak, and you don't multiply free, or trash the memory arena.

    Check also the heap chain, make sure you don't have an issue with fragmentation.

    Your code is sufficiently broken as presented that it needs fixing before further assessment would be useful.

Children