runtime error: addition of unsigned offset to 0x7ffeba23a6e0 - c++

Here is my code, I wrote it on leetcode platform
const int N1 = 100+1;
const int N2 = 10e4+1;
class Solution {
public:
bool cache[N1][N2];
bool isSubsequence(string s, string t) {
int n1 = s.size();
int n2 = t.size();
for(int i=0; i<=n1; i++) {
for(int j=0; j<=n2; j++) {
if(i == 0)
cache[i][j] = true;
if(j == 0)
cache[i][j] = false;
if(s[i-1] == t[j-1])
cache[i][j] = cache[i-1][j-1];
else
cache[i][j] = cache[i][j-1];
}
}
return cache[n1][n2];
}
};
It gives following error, I don't know why. Please help.
error image

We don't have to cache anything for solving this problem, we can totally do that in constant memory.
This'd pass by looping through t with just one if statement:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
using ValueType = std::uint_fast16_t;
static const struct Solution {
static const bool isSubsequence(
const std::string source,
const std::string target
) {
const ValueType s_len = std::size(source);
const ValueType t_len = std::size(target);
ValueType s_index = 0;
for (ValueType t_index = 0; t_index < t_len && s_index < s_len; ++t_index) {
if (target[t_index] == source[s_index]) {
++s_index;
}
}
return s_index == s_len;
}
};

I solved this issue. Error was because of array index out of bounds.
Here is the edit part:
if(i == 0)
cache[i][j] = true;
else if(j == 0)
cache[i][j] = false;
else if(s[i-1] == t[j-1])
cache[i][j] = cache[i-1][j-1];
else
cache[i][j] = cache[i][j-1];
};

Related

C++ program to count repeated words in a cstring

I've been working on a C++ program, I've made the logic but I'm unable to execute it. The question is:
Task: Write a program, using functions only, with the following features.
Program reads paragraph(s) from the file and stores in a string.
Then program counts the occurrence of each word in the paragraph(s) and stores all words with their number of occurrences.
If that word has appeared more than one time in whole string, it should store the word only once along its total occurrences.
The output described in above (in part 3) must be stored in a new file.
Sample input:
is the is and the is and the and is and only that is
Sample output:
is 5
the 3
and 4
only 1
that 1
I'll cut short to Occurrence program that I've written,
My logic is to store token into character array and then compare that array with main character array and do the increment:
void occurances() {
char* string = getInputFromFile();
char separators[] = ",.\n\t ";
char* token;
char* nextToken;
char* temp[100];
token = strtok_s(string, separators, &nextToken);
cout << temp;
int counter = 0;
int i = 0;
while ((token != NULL)) {
temp[i] = token;
i++;
for (int i = 0; i < strlen(string); i++) {
for (int j = 0; j < 100; j++) {
if ((strcmp(token, *temp)) == 0) {
counter++;
}
}
cout << temp << " : " << counter << endl;
}
if (token != NULL) {
token = strtok_s(NULL, separators, &nextToken);
}
}
}
This code is preposterous I know that, But please anyone be kind enough to give me a clue, actually I'm new to C++ . Thank you
If you store token into array this array should grow dynamically because the number of tokens is not known at the beginning. And according to the task description, you cannot use C++ standard containers, so, it is necessary to implement dynamic array manually, for example:
#include <iostream>
std::size_t increase_capacity_value(std::size_t capacity) {
if (capacity == 0) {
return 1;
}
else if (capacity < (SIZE_MAX / 2)) {
return capacity * 2;
}
return SIZE_MAX;
}
bool increase_array_capacity(char**& tokens_array, std::size_t*& tokens_count, std::size_t& capacity) {
const std::size_t new_capacity = increase_capacity_value(capacity);
if (new_capacity <= capacity) {
return false;
}
const std::size_t tokens_array_byte_size = new_capacity * sizeof(char*);
char** const new_tokens_array = static_cast<char**>(std::realloc(tokens_array, tokens_array_byte_size));
if (new_tokens_array == nullptr) {
return false;
}
tokens_array = new_tokens_array;
const std::size_t tokens_count_byte_size = new_capacity * sizeof(std::size_t);
std::size_t* const new_tokens_count = static_cast<std::size_t*>(std::realloc(tokens_count, tokens_count_byte_size));
if (new_tokens_count == nullptr) {
return false;
}
tokens_count = new_tokens_count;
capacity = new_capacity;
return true;
}
bool add_token(char* token, char**& tokens_array, std::size_t*& tokens_count, std::size_t& array_size, std::size_t& array_capacity) {
if (array_size == array_capacity) {
if (!increase_array_capacity(tokens_array, tokens_count, array_capacity)) {
return false;
}
}
tokens_array[array_size] = token;
tokens_count[array_size] = 1;
++array_size;
return true;
}
std::size_t* get_token_count_storage(char* token, char** tokens_array, std::size_t* tokens_count, std::size_t array_size) {
for (std::size_t i = 0; i < array_size; ++i) {
if (std::strcmp(token, tokens_array[i]) == 0) {
return tokens_count + i;
}
}
return nullptr;
}
bool process_token(char* token, char**& tokens_array, std::size_t*& tokens_count, std::size_t& array_size, std::size_t& array_capacity) {
std::size_t* token_count_ptr = get_token_count_storage(token, tokens_array, tokens_count, array_size);
if (token_count_ptr == nullptr) {
if (!add_token(token, tokens_array, tokens_count, array_size, array_capacity)) {
return false;
}
}
else {
++(*token_count_ptr);
}
return true;
}
int main() {
char string[] = "is the is and the is and the and is and only that is";
char separators[] = ",.\n\t ";
std::size_t token_array_capacity = 0;
std::size_t token_array_size = 0;
char** tokens_array = nullptr;
std::size_t* tokens_count = nullptr;
char* current_token = std::strtok(string, separators);
while (current_token != nullptr) {
if (!process_token(current_token, tokens_array, tokens_count, token_array_size, token_array_capacity)) {
break;
}
current_token = std::strtok(nullptr, separators);
}
// print the report only if all tokens were processed
if (current_token == nullptr) {
for (std::size_t i = 0; i < token_array_size; ++i) {
std::cout << tokens_array[i] << " : " << tokens_count[i] << std::endl;
}
}
std::free(tokens_array);
std::free(tokens_count);
}
godbolt.org
okay what if i want to store any token once, in an array and then replace it with new word while deleting duplicates in character array
It is also possible solution. But in general case, it is also necessary to allocate the memory dynamically for the current token. Because the lengths of tokens are also not known at the beginning:
void replace_chars(char* str, const char* chars_to_replace) {
while (str && *str != '\0') {
str = std::strpbrk(str, chars_to_replace);
if (str == nullptr) {
break;
}
const std::size_t number_of_delimiters = std::strspn(str, chars_to_replace);
for (std::size_t i = 0; i < number_of_delimiters; ++i) {
str[i] = '\0';
}
str += number_of_delimiters;
}
}
bool keep_token(char*& token_storage, const char* new_token) {
if (new_token == nullptr) {
return false;
}
const std::size_t current_token_len = token_storage ? std::strlen(token_storage) : 0;
const std::size_t requried_token_len = std::strlen(new_token);
if (token_storage == nullptr || current_token_len < requried_token_len) {
token_storage =
static_cast<char*>(std::realloc(token_storage, (requried_token_len + 1) * sizeof(char)));
if (token_storage == nullptr) {
return false;
}
}
std::strcpy(token_storage, new_token);
return true;
}
std::size_t count_tokens_and_replace(char* str, std::size_t str_len, const char* token) {
std::size_t number_of_tokens = 0;
std::size_t i = 0;
while (i < str_len) {
while (str[i] == '\0') ++i;
if (std::strcmp(str + i, token) == 0) {
replace_chars(str + i, token);
++number_of_tokens;
}
i += std::strlen(str + i);
}
return number_of_tokens;
}
int main() {
char string[] = "is the is and the is and the and is and only that is";
char separators[] = ",.\n\t ";
const std::size_t string_len = std::strlen(string);
replace_chars(string, separators);
std::size_t i = 0;
char* token = nullptr;
while (true) {
while (i < string_len && string[i] == '\0') ++i;
if (i == string_len || !keep_token(token, string + i)) break;
std::cout << token << " : " << count_tokens_and_replace(string + i, string_len - i, token) << std::endl;
}
std::free(token);
}
godbolt.org
But if it is known that the token length cannot be greater than N, it is possible to use the static array of chars to keep the current token. And it will allow to remove dynamic memory allocation from the code.

How to convert this JavaScript code to C++

Problem is to return any one combination from given array that sums up to the target. I'm new to C++. How can I complete the function howSum() below? I can't return null here since the return type is vector. Also I'm having trouble passing the vectors.
JavaScript:
const howSum = (targetSum, numbers) => {
if (targetSum === 0) return [];
if (targetSum < 0) return null;
for (let num of numbers) {
const remainder = targetSum - num;
const remainderResult = howSum(remainder, numbers);
if (remainderResult !== null)
{
return [...remainderResult, num];
}
}
return null;
};
C++:
vector<int> howSum(int targetSum, vector<int> numbers)
{
if(targetSum == 0) return {};
if(targetSum < 0) return; //can't return null here in C++
for (int i = 0; i < numbers.size(); i++)
{
int remainder = targetSum - numbers[i];
vector<int> remainderResult = howSum(remainder, numbers);
if(pass)
{
pass
}
}
}
You can use C++17 std::optional and return std::nullopt when it does not contain value.
#include <optional>
#include <vector>
std::optional<std::vector<int>>
howSum(int targetSum, const std::vector<int>& numbers) {
if (targetSum == 0)
return std::vector<int>{};
if (targetSum < 0)
return std::nullopt;
for (auto numer : numbers) {
const auto remainder = targetSum - numer;
auto remainderResult = howSum(remainder, numbers);
if (remainderResult) {
remainderResult->push_back(targetSum);
return remainderResult;
}
}
return std::nullopt;
}
Let your function return a bool to indicate if the vector result (returned as an out param) is valid or not. It's likely going to be more efficient to pass the array (vector) as an out param reference than as a return value anyway. (Although modern compilers can do some amazing optimizations these days.)
bool howSum(int targetSum, const std::vector<int>& numbers, std::vector<int>& result)
{
result.clear();
if (targetSum == 0) {
return true;
}
if (targetSum < 0) {
return false;
}
for (int num : numbers) {
const int remainder = targetSum - num;
bool recursion_result = howSum(remainder, numbers, result);
if (recursion_result) {
result.push_back(num);
return true;
}
}
return false;
}

Dynamic BigBinaryString implmentation in C++

I am writing a BigBinaryString class in C++ which abstractly holds the large binary string and can perform operations like xor, and, left shift and right shift.
I have stored the binary string internally as a vector of unsigned longs, so each element in vector consumes 64-bits from the bitstring.
I have decided to use have four types of constructors:
BigBinaryString(const string bitstring) //for directly converting the bitstring to internal repr.
BigBinaryString() //initialize the binary string to 0.
BigBinaryString(const size_t num) //hold the binary for corresponding unsigned long.
BigBinaryString(const vector<size_t> vec) //Directly pass the internal repr to the constructor for it to copy.
So far I have implemented and, xor, equality and left shift operators.
However, I feel the left shift operator has a very high time complexity in which the way I have implemented it.
So, I need a few suggestions on how to speed up the left shift operator so that I can implement the right shift efficiently as well.
The code so far is as follows:
#define SIZE_UNSIGNED_LONG (sizeof(size_t) * 8)
class BigBinaryString {
private:
vector<size_t> num;
void reduce() {
while (*num.rbegin() == 0) {
num.pop_back();
}
if (num.size() == 0) {
num.push_back(0);
}
}
public:
BigBinaryString() { num.push_back(0); }
BigBinaryString(const size_t n) { num.push_back(n); }
BigBinaryString(const vector<size_t> vec) {
const size_t length = vec.size();
for (size_t i = 0; i < length; i++) {
num.push_back(vec.at(i));
}
reduce();
}
BigBinaryString operator&(const BigBinaryString& op) {
vector<size_t> vec;
size_t maxlen = max(num.size(), op.num.size());
size_t minlen = min(num.size(), op.num.size());
const size_t zero = 0;
for (size_t i = 0; i < minlen; i++) {
vec.push_back(num.at(i) & op.num.at(i));
}
return BigBinaryString(vec);
}
BigBinaryString(const string bitstring) {
string temp = bitstring;
size_t dec = 0;
while (temp.length() != 0) {
if (temp.length() > SIZE_UNSIGNED_LONG) {
dec = stoul(temp.substr(temp.length() - SIZE_UNSIGNED_LONG,
SIZE_UNSIGNED_LONG),
nullptr, 2);
temp = temp.substr(0, temp.length() - SIZE_UNSIGNED_LONG);
} else {
dec = stoul(temp, nullptr, 2);
temp = "";
}
num.push_back(dec);
}
reduce();
}
BigBinaryString operator^(const BigBinaryString& op) {
vector<size_t> vec;
size_t maxlen = max(num.size(), op.num.size());
size_t minlen = min(num.size(), op.num.size());
for (size_t i = 0; i < maxlen; i++) {
if (i < minlen) {
vec.push_back(num.at(i) ^ op.num.at(i));
} else if (maxlen == num.size()) {
vec.push_back(num.at(i));
} else if (maxlen == op.num.size()) {
vec.push_back(op.num.at(i));
}
}
return BigBinaryString(vec);
}
bool operator==(const BigBinaryString& op) {
if (num.size() != op.num.size()) {
return false;
}
size_t length = num.size();
for (size_t i = 0; i < length; i++) {
if (num.at(i) != op.num.at(i)) {
return false;
}
}
return true;
}
bool operator==(const size_t n) {
BigBinaryString op(n);
if (num.size() != op.num.size()) {
return false;
}
size_t length = num.size();
for (size_t i = 0; i < length; i++) {
if (num.at(i) != op.num.at(i)) {
return false;
}
}
return true;
}
bool operator!=(const BigBinaryString& op) { return not(*this == op); }
bool operator!=(const size_t op) { return not(*this == op); }
BigBinaryString operator<<(size_t shift) {
string bitstring = this->to_string();
bitstring.append(shift, '0');
return BigBinaryString(bitstring);
}
string to_string() {
string suffix = "";
string retval = "";
string prefix = "";
size_t n = 0;
for (auto i = num.rbegin(); i != num.rend(); i++) {
n = *i;
prefix.clear();
suffix.clear();
while (n != 0) {
suffix = (n % 2 == 0 ? "0" : "1") + suffix;
n /= 2;
}
if (i != num.rbegin()) {
prefix.append(SIZE_UNSIGNED_LONG - suffix.size(), '0');
}
prefix = prefix + suffix;
if (prefix.size() == SIZE_UNSIGNED_LONG) {
retval += prefix;
} else if (i == num.rbegin()) {
retval += prefix;
} else if (i != num.rbegin()) {
throw invalid_argument("prefix+suffix error");
}
}
return retval;
}
};
Any help will be appreciated!

heap corruption?Windows has triggered a breakpoint in SwiftIndex.exe

I know that similar question has been asked,but I still can not figure out what is wrong.As mentioned above,I am debugging a program with VS2010 which always telling me "This may be due to a corruption of the heap, which indicates a bug in SwiftIndex.exe or any of the DLLs it has loaded...".So,here is part of my code:
Status PrefixQuickSI::my_QucikSI(std::vector<_QISymbol> &cur_sequence, QISequence graphcode, int depth, int feature_size, ECVector<char> cur_UsageTab, ECVector<SequenceIndex> cur_MappingTab, bool &flag)
{
Status st;
int vcnt = m_QueryGraph->V();
_QISymbol T;
if(depth == 0)
{
T.tSymbol = graphcode.sequence[depth]->tSymbol;
T.rSymbols.clear();
for(int i = 0; i < graphcode.sequence[depth]->numOfRSymbol; i++)
{
int v1,v2;
Label elabel;
v1 = graphcode.sequence[depth]->rSymbol[i].val;
v2 = graphcode.sequence[depth]->rSymbol[i+1].val;
elabel = graphcode.sequence[depth]->rSymbol[i].lable;
if(m_QueryGraph->getELabel(cur_MappingTab[v1],cur_MappingTab[v2]) != elabel)
{
flag = false;
return OK;
}
T.rSymbols.push_back(graphcode.sequence[depth]->rSymbol[i]);
T.rSymbols.push_back(graphcode.sequence[depth]->rSymbol[i+1]);
i++;
}
depth++;
cur_sequence.push_back(T);
if(depth == graphcode.numOfPrefixNode)
{
flag =true;
return OK;
}
else
{
st = my_QucikSI(cur_sequence, graphcode,depth, feature_size, cur_UsageTab, cur_MappingTab, flag);
if(flag == true)
{
return OK;
}
else
{
flag = false;
return OK;
}
}
}
else
{
T.tSymbol = graphcode.sequence[depth]->tSymbol;
for( int j = 0; j < graphcode.sequence[depth]->numOfRSymbol; ++j )
{
RSymbol rSymbol;
rSymbol = graphcode.sequence[depth]->rSymbol[j];
T.rSymbols.push_back(rSymbol);
}
int pV;
VertexIDSet Vcandiates;
for( int i = 0; i < vcnt; i++ )
{
pV = T.tSymbol.p;
if( cur_UsageTab[i] > 0 || m_QueryGraph->getLabel(i) != T.tSymbol.l || m_QueryGraph->getELabel(i, cur_MappingTab[pV]) != T.tSymbol.pl)
continue;
Vcandiates.insert(i);
}
for( VertexIDSet::const_iterator v = Vcandiates.begin(); v != Vcandiates.end(); v++ )
{
bool mis_match = false;
for( std::vector<RSymbol>::const_iterator r = T.rSymbols.begin(); r != T.rSymbols.end(); r++ )
{
if( !MatchREntry(cur_sequence, *v, *r) )
{
mis_match = true;
break;
}
}
if( mis_match )
continue;
cur_MappingTab[feature_size + depth] = *v;
cur_UsageTab[*v] = 1;
depth++;
cur_sequence.push_back(T);
if(depth == graphcode.numOfPrefixNode)
{
flag = true;
return OK;
}
else
{
st = my_QucikSI(cur_sequence, graphcode,depth, feature_size, cur_UsageTab, cur_MappingTab,flag);
if(flag == true)
{
return OK;
}
else
{
cur_UsageTab[*v] = 0;
depth--;
}
}
}
}
return OK;
}
and the calling function statement is:
int depth = 0;
st = my_QucikSI(cur_sequence, datacodes[cur_graphid], depth, cur_size,cur_UsageTab,cur_MappingTab, flag);
I have debugged step by step,and found that the "heap corruption" occurred in the second return of the recursion of function my_QuickSI(flag already equaled true at the third recursion and function returned to the second recursion,when it's about to return to the first recursion,the "heap corruption" happened).
Hope someone find where the problem is.
You can find my previous answer useful for your problem:
https://stackoverflow.com/a/22074401/2724703
In general heap corruption is often detected after the real corruption has already occurred by some DLL/module loaded within your process.

Why I am getting zero output for all the values in array?

I got this implementation for maximum matching off the net and is trying to give its input through main class. But I am getting zero for all the places in match. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
using namespace std;
void add_edge(int u, int v);
void edmonds();
struct edge {
int v, nx;
};
const int MAXN = 1000, MAXE = 2000;
edge graph[MAXE];
int last[MAXN], match[MAXN], px[MAXN], base[MAXN], N, M, edges;
bool used[MAXN], blossom[MAXN], lused[MAXN];
int main ()
{
// return 0;
add_edge(1,4);
add_edge(1,5);
add_edge(1,6);
add_edge(2,5);
add_edge(2,7);
add_edge(3,4);
add_edge(4,1);
add_edge(4,3);
add_edge(5,1);
add_edge(5,2);
add_edge(6,1);
add_edge(7,2);
edmonds();
cout << match[0];
cout << match[1];
cout << match[2];
cout << match[3];
cout << match[4];
cout << match[5];
cout << match[6];
}
inline void add_edge(int u, int v) {
graph[edges] = (edge) {v, last[u]};
last[u] = edges++;
graph[edges] = (edge) {u, last[v]};
last[v] = edges++;
}
void mark_path(int v, int b, int children) {
while (base[v] != b) {
blossom[base[v]] = blossom[base[match[v]]] = true;
px[v] = children;
children = match[v];
v = px[match[v]];
}
}
int lca(int a, int b) {
memset(lused, 0, N);
while (1) {
lused[a = base[a]] = true;
if (match[a] == -1)
break;
a = px[match[a]];
}
while (1) {
b = base[b];
if (lused[b])
return b;
b = px[match[b]];
}
}
int find_path(int root) {
memset(used, 0, N);
memset(px, -1, sizeof(int) * N);
for (int i = 0; i < N; ++i)
base[i] = i;
used[root] = true;
queue<int> q;
q.push(root);
register int v, e, to, i;
while (!q.empty()) {
v = q.front(); q.pop();
for (e = last[v]; e >= 0; e = graph[e].nx) {
to = graph[e].v;
if (base[v] == base[to] || match[v] == to)
continue;
if (to == root || (match[to] != -1 && px[match[to]] != -1)) {
int curbase = lca(v, to);
memset(blossom, 0, N);
mark_path(v, curbase, to);
mark_path(to, curbase, v);
for (i = 0; i < N; ++i)
if (blossom[base[i]]) {
base[i] = curbase;
if (!used[i]) {
used[i] = true;
q.push(i);
}
}
} else if (px[to] == -1) {
px[to] = v;
if (match[to] == -1)
return to;
to = match[to];
used[to] = true;
q.push(to);
}
}
}
return -1;
}
void build_pre_matching() {
register int u, e, v;
for (u = 0; u < N; ++u)
if (match[u] == -1)
for (e = last[u]; e >= 0; e = graph[e].nx) {
v = graph[e].v;
if (match[v] == -1) {
match[u] = v;
match[v] = u;
break;
}
}
}
void edmonds() {
memset(match, 0xff, sizeof(int) * N);
build_pre_matching();
register int i, v, pv, ppv;
for (i = 0; i < N; ++i)
if (match[i] == -1) {
v = find_path(i);
while (v != -1) {
pv = px[v], ppv = match[pv];
match[v] = pv, match[pv] = v;
v = ppv;
}
}
}
You set elements of match in two locations: In build_pre_matching() and in edmonds(). In both of these cases, no change will happen if match[x] for some index x isn't -1. The only other place elements of match get a value is during static initialization where the values get zero initialized. Since the initial value is zero and the values are only ever changed if at least one of them happens to be -1, I would expect that the values retain the value 0.
You might want to use something like
std::fill(std::begin(match), std::end(match), -1);
at a strategic location since you seem to assume that the values are initially -1. Of course, you also should consider the idea of not using global variables because this doesn't scale and works really badly in a multi-threaded program.