为什么传入的字符串在打印两次以上时会有所不同

Why the incoming string is different when print it out more than twice?

本文关键字:两次 有所不同 字符串 打印 为什么      更新时间:2023-10-16
int deleteFile(const char* filePath)
{
    int rc;
    int retVal ;
    logPrint("filePath=%s n",filePath);  
    logPrint("call delete file,  filePath=%s n",filePath);
    if( (rc=FileHelper::DeleteFile(filePath)) == true &&
        FileHelper::FileExists(filePath) == false)
    {
          logPrint(" file deleted successfully n");    
          retVal = 1;   
    }
    else
    {
         logPrint(" file deleted failed n");       
         retVal = -1;
    }
    return retVal;
}

第一个logPrint("filePath=%s n",filePath);

打印出来 :

"mntappdatafile.db"

然而,第二个logPrint("call delete file, filePath=%s n",filePath);

打印出来 :

"call delete file, call delete file"

所以文件路径似乎已更改。在 deleteFile(( 返回之前它是如何更改的?

看起来调用方函数使用不属于它的缓冲区来存储"filePath"并将指针传递给您的函数。日志打印函数显然在您的情况下使用的缓冲区。下面是调用方行为的一个示例:

     const char* getFilePath(){
           const char* p= "mntappdatafile.db";      
           return p;
     }
     void caller_function(){
           int ret;
           const char * path = getFilePath();    
           ret =  deleteFile(path);
           if(ret != 1)
               printf("delete File failed ");
           return;
     } 
getFilePath(( 使用本地缓冲区 (

char * p( 来保存文件路径,并将此本地缓冲区指针 p 传递给 caller_function((。返回 getFilePath(( 后,从堆栈中释放本地缓冲区内存。缓冲区可由任何函数自由使用。C 使用了很多通过引用传递,作为程序员,你必须非常小心,并确保在函数完成时引用缓冲区不会被破坏。

解决此问题的一种方法是使用静态缓冲区来存储文件路径,"static const"变量创建一次,并且在函数退出时不会销毁。

      const char* getFilePath(){
           static const char* p= "mntappdatafile.db";      
           return p;
      }