c - Free() segfault on PIC24 -


i have 2 16-bit pointers being allocated @ runtime, in order save long doubles flash (using microchip dee flash emulation library). code works fine, , recalls saved values correctly, if use free() on malloc()'d pointers, code segfaults @ next malloc() call (in function, in section of code).

void readmiccaldata(microphone* pmicread) { /* allocate space 2*16-bit pointers */ int16_t* tempflashbuffer = (int16_t*)malloc(sizeof(int16_t)); int16_t* tempflashbuffer2 = (int16_t*)malloc(sizeof(int16_t));  if ((tempflashbuffer == null) || (tempflashbuffer2 == null)) {     debugmessage("\n\rheap> failed allocate memory flash buffer!\n\r",1); }  /* increment through 2-byte blocks */ wc1 = rcm_mic_cal_start_address; while(wc1 < rcm_mic_cal_end_address) {      /* init pointer lowest 16-bits of 32-bit value e.g. 0x0d90 */     tempflashbuffer = (int16_t*) &pmicread->factor_db[i4];      /* save pointer , increment next 16-bit address e.g. 0x0d92 */     tempflashbuffer2 = tempflashbuffer + 1;      /* read first 16-bit value */     *tempflashbuffer = dataeeread(wc1);      /* catch 0xffff , set zero. otherwise float becomes nan. */     if (*tempflashbuffer == 0xffff) { *tempflashbuffer = 0; }      /* read next 16-bits of value */     *tempflashbuffer2 = dataeeread(wc1 + 1);      if (*tempflashbuffer2 == 0xffff) { *tempflashbuffer2 = 0; }      /* move next 2*16-bit block of memory */     wc1 = wc1 + 2;      /* move next saved mic. cal. frequency */     i4++; }  /* free memory */ free(tempflashbuffer); free(tempflashbuffer2); } 

could tempflashbuffer2 assignment counting increment? therefore i'm not free()ing same pointer assigned malloc()?

if don't free() 2 pointers, code runs fine , doesn't see segfaults (at least not in short term!).

the pointers passed free() must pointer returned previous call malloc(), calloc() or realloc(). not case here changing pointer values, causing undefined behaviour. section 7.20.3.2 free function of c99 standard:

the free function causes space pointed ptr deallocated, is, made available further allocation. if ptr null pointer, no action occurs. otherwise, if argument not match pointer earlier returned calloc, malloc, or realloc function, or if space has been deallocated call free or realloc, behavior undefined.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -