I am solving a question on leetcode where I have to multiply strings and I got this error which I cant understand
Line 518: Char 69: runtime error: applying non-zero offset 18446744073709551615 to null pointer (basic_string.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/basic_string.h:527:69
Here is my code
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;
}
For the case where ans=""
,
Instead of returning "0"
(string), you are returning 0
(Integer).
As the return type is a string it is causing a problem.
if(ans=="")
{
return "0";
}
This Should work fine, I think.