动态申请内存与释放时的异常---Byte越界(CheckBytes函数的内部机制)

本文详细介绍了在C++中使用宽字符进行内存申请时,遇到LoadLibrary函数异常的问题,以及如何通过多申请内存空间解决该问题。通过分析内存布局和CheckBytes函数的工作原理,解释了异常产生的原因,并提供了避免此类问题的方法。

http://blog.youkuaiyun.com/zp373860147/article/details/6992647

今天在堆代码的时候,堆了下面一段代码,Debug时异常,Release没问题。

[html]  view plain copy
  1. const std::string &sFilename;  
  2. wchar_t  *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(sFilename.length()-1));  
  3.   m_hDLL = ::LoadLibrary(/*stringToLPCWSTR(sFilename)*/stringToLPCWSTR(sFilename,wcstring));  
  4.   if (wcstring)  
  5.   {  
  6.       delete []wcstring;  
  7.   }  
  8.   wcstring = NULL;  
其实很简单,得到一个const std::string &类型的参数sFilename,想通过它来加载dll,但是::LoadLibrary的参数是LPCWSTR类型,就自己写个函数

[html]  view plain copy
  1. LPCWSTR stringToLPCWSTR(std::string orig, wchar_t * wcstring)  

来转换一下。

然后就在转换前动态申请了内存,并在使用后释放,如下:

[html]  view plain copy
  1. wchar_t  *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(sFilename.length()-1));  
  2. .......................................  
  3.   if (wcstring)  
  4.   {  
  5.       delete []wcstring;  
  6.   }  
  7.   wcstring = NULL;  
看起来貌似没问题,但是Debug异常了,问题出在delete []wcstring;这句,果断跟进去,最后跟进n层后定位到下面这个函数

[html]  view plain copy
  1. extern "C" static int __cdecl CheckBytes(  
  2.         unsigned char * pb,  
  3.         unsigned char bCheck,  
  4.         size_t nSize  
  5.         )  
  6. {  
  7.         int bOkay = TRUE;  
  8.         while (nSize--)  
  9.         {  
  10.             if (*pb++ != bCheck)  
  11.             {  
  12. /* Internal error report is just noise; calling functions all report results - JWM */  
  13. /*                _RPT3(_CRT_WARN, "memory check error at 0x%p = 0x%02X, should be 0x%02X.\n", */  
  14. /*                    (BYTE *)(pb-1),*(pb-1), bCheck); */  
  15.                 bOkay = FALSE;  
  16.             }  
  17.         }  
  18.         return bOkay;  
  19. }  

这个函数的作用是检查指定范围内的Byte是否被更改,如果被更改,返回false,如果未更改,返回true;

第一个参数是一个指针,第二个参数是用来进行比较的值,第三个参数是从指定位置(第一个指针表示)起,检测的位数。调试发现,bCheck为253,对应16进制为fd,nSize为4,下面查看内存,如图:

可以看到第一行中连续6个ab的前面有3个连续的00 ,其中第一个00是与其左边的6e共同组成一个Unicode宽字符,对应字符n,后两个连续的00组成宽字符\0,也就是从这个位置开始,CheckByte函数开始向后检测4位,看其是否是fd,由图可知,显然不是,所以返回false,抛出异常


下面,如果我申请的内存这么写:

[html]  view plain copy
  1. wchar_t  *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(sFilename.length()-1)<span style="color:#FF0000;">+2</span>);  
即多申请两个字节,内存图如下:

可以看到连续的00后只有2个fd,调试仍然失败


下面,多申请4个字节:

[html]  view plain copy
  1. wchar_t  *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(sFilename.length()-1)<span style="color:#FF0000;">+4</span>);  

可以看到现在内存中连续的00后有了四个fd,调试不再抛异常。

最后,在以上三种情况下,通过查看CheckByte的第一个参数pb发现,pb总是我们申请的内存空间的末尾位置向前移动2个字节(如果算上编译器自动加上的用于存放\0的2个字节,那就是向前移动4个字节)。也就是说,如果我们申请的内存不足够大,那么编译器将无法在其末尾找到连续4个fd,他就会认为内存越界而异常。


经验就是,在使用宽字符的时候多申请一些空间,最小也得多申请4个。

char的时候没试验,应该也是同样的道理。


The whole source code can be downloaded from our download center. /******************************************************************************* Function Name : main Description : Main program. Input : None Output : None Return : None *****************************************************************************/ void main(void) { ENTR_CRT_SECTION(); / Setup STM32 system (clock, PLL and Flash configuration) / SystemInit(); EXT_CRT_SECTION(); // Choose your Slot (SPI1, SPI2) void Bus_Type = SPI1; / controlled loop / while (Dummy_var!=11) // To control the loop, e.g. (Dummy_var!=7) { if (Dummy_var10) Dummy_var=0; // Infinite loop if(configured_trueFALSE) { configured_true = TRUE; SPIx_GPIOs_Init(Bus_Type); SPIx_Interface_Init(Bus_Type); #ifdef EMBEDDED_SRAM Embed_SRAM_Init(); #endif Ext_Interrupt_Init(); gp22_send_1byte(Bus_Type, Power_On_Reset); Dly100us((void)5); // 500 us wait for GP22 // Setting of the Configuration Registers // CR0: DIV_CLKHS = 2, START_CLKHS = 1, CALIBRATE = 0, MESSB2 = 0, NEG_STOP = NEGSTART = 0, … Register_0 = 0x00240000; // NO_CAL_AUTO = 0 Register_0_NO_CAL = 0x00241000; // NO_CAL_AUTO = 1 // CR1: HITIN2 = 1, HITIN1 = 1, … Register_1 = 0x19490000; // EN_FAST_INIT = 0 Register_1_FAST = 0x19C90000; // EN_FAST_INIT = 1 // CR2: EN_INT, RFEDGE1 = RFEDGE2 = 0, … // (NOTE: EN_INT = b111, it doesn’t work with using EN_FAST_INT) Register_2 = 0xA0000000; // EN_INT = Timeout(8) _ End HITs(4) _ ALU interrupt(2) // CR3: … Register_3 = 0x00000000; // CR4: ... Register_4 = 0x20000000; // CR5: CON_FIRE = b000, EN_STARTNOISE = 1, ... Register_5 = 0x10000000; // CR6: QUAD_RES = 0, ... Register_6 = 0x00000000; // Writing to the configuration registers (CR) gp22_wr_config_reg(Bus_Type, 0x80, Register_0_NO_CAL); gp22_wr_config_reg(Bus_Type, 0x81, Register_1_FAST); gp22_wr_config_reg(Bus_Type, 0x82, Register_2); gp22_wr_config_reg(Bus_Type, 0x83, Register_3); gp22_wr_config_reg(Bus_Type, 0x84, Register_4); gp22_wr_config_reg(Bus_Type, 0x85, Register_5); gp22_wr_config_reg(Bus_Type, 0x86, Register_6); } // ......................................................................... // ...START_CAL_RESONATOR..Calibrate High Speed Clock....................... // ...START_CAL_TDC.....Update the CAL2- and CAL1-Value..................... // ...................Laser Rangefinder Measurement CYCLE............LOOP... // .........................Caluculate Result Values........................ N_Measure_Cycles = 10000; diff_Cal2_Cal1_old = diff_Cal2_Cal1_new; if((Dummy_var==0) | (Dummy_var==10)) { //-------------------------------------------------------------------------- // Start Calibrate High Speed Clock Cycle (-->SLOW) // Important Note: NO_CAL_AUTO and EN_FAST_INIT need to be cleared! gp22_wr_config_reg(Bus_Type, 0x80, Register_0); // NO_CAL_AUTO = 0 gp22_wr_config_reg(Bus_Type, 0x81, Register_1); // EN_FAST_INIT = 0 gp22_send_1byte(Bus_Type, Init); gp22_send_1byte(Bus_Type, Start_Cal_Resonator); // Wait for INT Slot_x if (Bus_Type==SPI1) while (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_4)==1); if (Bus_Type==SPI2) while (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_11)==1); //Calculate Correction factor //The time interval to be measured is set by ANZ_PER_CALRES //which defines the number of periods of the 32.768 kHz clock: //2 periods = 61.03515625 µs CLKHS_freq_corr_fact = 61.03515625/ gp22_read_n_bytes_int(Bus_Type, 2, 0xB0, 0x00) * CLKHS_freq; // read only two bytes printf("\n Correction factor for clock = %1.4f\n", CLKHS_freq_corr_fact); CLKHS_freq_cal = CLKHS_freq * CLKHS_freq_corr_fact; // Calibrated Clock frequency //-------------------------------------------------------------------------- // Start Separate Calibration Measurement Cycle // Important Note: EN_INT = End HITs gp22_wr_config_reg(Bus_Type, 0x82, 0x40000000); // End HITs gp22_send_1byte(Bus_Type, Init); gp22_send_1byte(Bus_Type, Start_Cal_TDC); // update calibration data // Note: // The calibration data are not addressed directly after the calibration // measurement but after the next regular measurement; // Wait for INT Slot_x if (Bus_Type==SPI1) while (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_4)==1); if (Bus_Type==SPI2) while (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_11)==1); // Important Note: After Separate Calibration Measurement Cycle // EN_INT = ALU interrupt gp22_wr_config_reg(Bus_Type, 0x82, Register_2); // Timeout + ALU interrupt //-------------------------------------------------------------------------- // 1st ToF Measurement plus calibration data readout // Note: (NO_CAL_AUTO = 0 / EN_FAST_INIT = 0) --> SLOW gp22_send_1byte(Bus_Type, Init); //Trigger pulse laser // SetPortHigh; GPIO_SetBits(GPIOD, GPIO_Pin_8); // Output HIGH // SetPortLow; GPIO_ResetBits(GPIOD, GPIO_Pin_8); // Output LOW // Wait for INT Slot_x if (Bus_Type==SPI1) while (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_4)==1); if (Bus_Type==SPI2) while (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_11)==1); // First regular measurement (to readout calibration data) RAW_Result_int = gp22_read_n_bytes_int(Bus_Type,2,0xB0,0x00); // read only two bytes #ifdef EMBEDDED_SRAM Write_Emb_SRAM_uint32_t(RAW_Result_int); // writes the first value into SRAM #endif // printf("\n 1. Measured RAW Value = %u \n",RAW_Result_int); // RAW value // Check Status Register, next free result register // printf("Stat_Reg = 0x%04X \n",gp22_read_status_bytes(Bus_Type)); // readout the new calibration data from result register adr 0x01 gp22_wr_config_reg(Bus_Type, 0x81, 0x67490000); diff_Cal2_Cal1_new = gp22_read_n_bytes_int(Bus_Type,2,0xB0,0x01); // read only two bytes #ifdef EMBEDDED_SRAM Write_Emb_SRAM_uint32_t(diff_Cal2_Cal1_new); #endif } //-------------------------------------------------------------------------- // Calculate the real time after the hole first cycle loop while (diff_Cal2_Cal1_old != 0) { avg_diff_Cal2_Cal1 = (diff_Cal2_Cal1_new+diff_Cal2_Cal1_old) / 2; // printf("\n OLD Cal2-Cal1 RAW Value = %.0f \n",diff_Cal2_Cal1_old); // printf("\n NEW Cal2-Cal1 RAW Value = %.0f \n",diff_Cal2_Cal1_new); average_RAW_Result /= N_Measure_Cycles; // Used Formulas: // --------------------------------------------------- // T_ref // Time_Value = ----------- * measured_RAW_Value // Cal2-Cal1 // --------------------------------------------------- // velocity_of_light // Distance_Value = ------------------- * Time_Value // 2 // --------------------------------------------------- // For this Source Code would be a Reference Clock used with 1 MHz Time_Result = (average_RAW_Result/avg_diff_Cal2_Cal1) * 1000;//time [ns] Distance_Result = Time_Result / 6.671281904; //distance [m] printf("\n Time Measure Result (ToF) = %.3f ns\n",Time_Result); printf(" corresponds to %.3f m of Distance\n",Distance_Result); printf(" to reflected point after %u Measurements\n",N_Measure_Cycles); diff_Cal2_Cal1_old = 0; } //-------------------------------------------------------------------------- // if more than one measure cycle (-->FAST) average_RAW_Result = RAW_Result_int; // set first value of average_RAW_Result gp22_wr_config_reg(Bus_Type, 0x80, Register_0_NO_CAL); // NO_CAL_AUTO = 1 gp22_wr_config_reg(Bus_Type, 0x81, Register_1_FAST); // EN_FAST_INIT = 1 gp22_send_1byte(Bus_Type, Init); //-------------------------------------------------------------------------- // n'th ToF Measurement for (int i=2; i<=N_Measure_Cycles;i++) { //Trigger pulse laser // SetPortHigh; GPIO_SetBits(GPIOD, GPIO_Pin_8); // Output HIGH // SetPortLow; GPIO_ResetBits(GPIOD, GPIO_Pin_8); // Output LOW // Wait for INT Slot_x if (Bus_Type==SPI1) while (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_4)==1); if (Bus_Type==SPI2) while (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_11)==1); RAW_Result_int = gp22_read_n_bytes_int(Bus_Type,2,0xB0,0x00); // read only two bytes // printf(" %u. Measure RAW Value = %.0f \n",i,RAW_Result_int); // RAW value average_RAW_Result += RAW_Result_int; #ifdef EMBEDDED_SRAM Write_Emb_SRAM_uint32_t(RAW_Result_int); // writes the next values into SRAM #endif } printf("\nNEW CYCLE...\n"); Dummy_var++; // To Control the loop #ifdef EMBEDDED_SRAM // clear internal SRAM of µC sram_mem_offset = 0x0; #endif } // End while Dummy_var } //End main
最新发布
08-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值