Heap usage error detected MALLOC.LIB

Hello,

I work with a rabbit 4300 and Dynamic C 10.72.
I’ve got errors with using of malloc() function, here is the error :

Run time error : Heap usage error detected
file : MALLOC.LIB
function : mspace_free
line : 3313

Here’s the code using the dynamic allocation to create an array of chars with the size of the file in the SD into a function :

char* fatInit_and_Read() // Initialisation du contexte FAT et lecture du fichier datas.txt
{
	int cr; // Déclaration des variables
   unsigned long size;
   fat_part* partition = NULL;
   FATfile datas_txt;
   char* buffer = NULL;

   cr = fat_AutoMount(FDDF_USE_DEFAULT);

   if(cr==0)
   {
   	partition = getPart(); // Connection à la carte SD
   }
   else
   {
      printf("ERREUR : Impossible d'ouvrir la carte SD !");ln;ln;
   }

   if(partition != NULL) // Ouverture du fichier
	{
	   cr = fat_Open(partition, "DATAS.TXT", FAT_FILE, 0, &datas_txt, NULL);
	   if(cr!=0)
	   {
	      printf("ERREUR : Aucun fichier DATAS.TXT n'a ete trouve ! ( %d )", cr);ln;ln;
	   }
      else
      {
	      fat_FileSize(&datas_txt, &size); // Calcul de la taille du fichier
	      buffer = malloc((size32_t)size); // Allocation d'un buffer

	      cr = fat_Read(&datas_txt, buffer, size*sizeof(char));  // Lecture du fichier
      }
	}
	else
	{
	   printf("ERREUR : Aucune carte SD n'a ete trouvee !");ln;ln;
	}

   fat_Close(&datas_txt); // Fermeture du fichier
   fat_UnmountDevice(partition->dev); // Déconnection de la carte SD

   return buffer;
}

After manipulation of my array “buffer” in the main(), i free it : free(buffer) ;

May you help me please to resolve the error ?
I’m sorry for my english.

Thanks for your help.

Your problem is that malloc() returns a far pointer and your code is using a near pointer. You are doing 2 things, first you are putting your data into some random memory location and second you are passing a non valid pointer into free() which is why you are getting an error.

Yopu could try using _root_malloc() and _root_free() if your file size is small.

Regards,
Peter

It works ! Thanks for your prompt answer.