c++ - 运行时错误 : applying non-zero offset 18446744073709551615 to null pointer (basic_string. h)

标签 c++ algorithm math data-structures number-theory

我正在解决 leetcode 上的一个问题,我必须将字符串相乘,但出现了这个我无法理解的错误

第 518 行:字符 69:运行时错误:将非零偏移量 18446744073709551615 应用于空指针 (basic_string.h) 摘要:UndefinedBehaviorSanitizer:未定义行为/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h :527:69

这是我的代码

string multiply(string s1, string s2) {
         vector<int> vec(s1.length()+s2.length(),0);
       for(int i=s2.length()-1;i>=0;i--){
           for(int j=s1.length()-1;j>=0;j--){
               int pro = (s1[j]-'0')*(s2[i]-'0') ;
               //borrow sent to next
               int sum = vec[i+j+1] + pro;
                vec[i+j+1] = (sum%10);
                vec[i+j] += (sum/10);
           }
       }
       string ans="";
       for(int i=0; i<(s1.length()+s2.length());i++){
           if(ans=="" && vec[i]==0){
               continue;
           }
           ans.push_back(vec[i]+'0');
       }
       if(ans==""){
           return 0;
       }
       return ans;

    }

链接:https://leetcode.com/problems/multiply-strings/

最佳答案

       if(ans==""){
           return 0;
       }

很糟糕。此函数返回字符串,因此 return 0; 表示 return string(0);

假设这里的字符串std::string 、构造函数

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

将用于此。

这意味着请求将nullptr(从0转换)转换为字符串,但这是无效的。

你应该使用

       if(ans==""){
           return "0";
       }

相反。

关于c++ - 运行时错误 : applying non-zero offset 18446744073709551615 to null pointer (basic_string. h),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66869520/

相关文章:

c++ - TravisCI 中的混合 C 和 C++ 项目

c++ - 如何从 post 请求的 HTTP 正文中提取二进制文件内容?

c# - 有条件的随机播放列表

algorithm - 找到最大的连续段算术级数

algorithm - 如何使用 MATLAB 求解此 PDE

c# - 如何找到图像的旋转角度?

c++ - 使用 aruco 和 opencv4 的未解析符号

c++ - 如何在异构容器上使用 boost::fusion::transform?

algorithm - 无三个连续元素的递归最大子序列和

python - Python 中的最大似然函数