Error: Char 34: runtime error: addition of unsigned offset to 0x603000000070 overflowed to 0x60300000006c (stl_vector.h) (C++) - c++

I have been trying to solve the sorted Squares leetcode problem (https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3240/), and I am mostly through it. However, I get the above error. Following is my code
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int start = 0;
int end = nums.size()-1;
vector<int> final(nums.size());
int finalIdx = final.size()-1;
int sqr = 0;
while(start<=end){
if (abs(nums[start])<abs(nums[end])){
sqr = nums[end]*nums[end];
final[finalIdx] = sqr;
finalIdx--;
end--;
}
if (abs(nums[start])>abs(nums[end])){
sqr = nums[start]*nums[start];
final[finalIdx] = sqr;
finalIdx--;
start++;
}
else if(abs(nums[start])==abs(nums[end])){
sqr = nums[end]*nums[end];
final[finalIdx] = sqr;
finalIdx--;
final[finalIdx] = sqr;
finalIdx--;
start++;
end--;
}
return final;
}
}
};
The issue lies in my loop condition I believe. When I change the condition to start<end, I have no compile error, but the first element of the output array (final) is always 0, which I assume is by default. However, when I try to do start<=end in order to add a condition that handles the start==end case, I get the above error. I would like to understand why this is happening so I can rectify the issue. Thanks!

First, that's not a "compile error" ; it's a runtime error (and the error message reported says as much.
That said, the issue stems from the condition of start <= end landing on the = part of that condition. Eventually that is guaranteed to happen, save for one very specific set of circumstances:
start = (end-1)
abs(num[start]) == abs(num[end])
When that happens, your code will dump two values to the output vector, and both increment start and decrement end. The start and end indexes effectively swap values, the while condition is no longer true, and the loop will now cleanly exit.
In all other circumstances start and end will eventually land on the same index. When that happens your dual-push logic will dump the same value twice into the target vector, and that is where the issue manifests. There is only one value left to push (and start and end both reference it by index). Therefore you're going to push one more value into your target vector than you have space for, and the runtime exception ensues.
The fix is simple. Stop trying to be smart about short circuiting in three different conditions when in reality you only need one and a master-else. The computational requirements are the same no matter what, and in the end all you need is this:
class Solution
{
public:
std::vector<int> sortedSquares(std::vector<int> const &nums)
{
std::vector<int> final(nums.size());
int start = 0;
int end = nums.size()-1;
int finalIdx = final.size()-1;
while(start<=end)
{
if (abs(nums[end]) < abs(nums[start]))
{
final[finalIdx--] = nums[start]*nums[start];
++start;
}
else
{
final[finalIdx--] = nums[end]*nums[end];
--end;
}
}
return final;
}
};
If you really want all three conditions in your code, it is possible, but not warranted, and the special case circumstances don't justify doing it. Regardless, see below:
class Solution
{
public:
std::vector<int> sortedSquares(std::vector<int> const &nums)
{
std::vector<int> final(nums.size());
int start = 0;
int end = nums.size() - 1;
int finalIdx = final.size() - 1;
while (start <= end)
{
if (abs(nums[start]) < abs(nums[end]))
{
final[finalIdx--] = nums[end] * nums[end];
end--;
}
else if (abs(nums[end]) < abs(nums[start]))
{
final[finalIdx--] = nums[start] * nums[start];
start++;
}
else // !(a<b || b<0) implies (a == b)
{
int sqr = final[finalIdx--] = nums[end] * nums[end];
if (end != start)
{
final[finalIdx--] = sqr;
}
--end;
++start;
}
}
return final;
}
};

Related

C++ There is a bool return type function returning (24) here

First of all sorry for too much code
Here there is a vector (teamNum) with type class, the class contain a vector (player) with type struct, it is a little complicated, but here in this function I need to check if there is a player in teamNum which contain tName equal to _tname (function parameter) contain (the player) pID equal to _pID (function parameter)
bool thereIsSimilarID(string _tname, int _pID)
{
for (int i = 0; i < teamNum.size(); i++)
{
if (teamNum[i].tName == _tname)
{
for (int j = 0; j < teamNum[i].player.size(); j++)
{
if (teamNum[i].player[j].pID == _pID)
return true;
}
}
else if (i == (teamNum.size() - 1))
{
return false;
}
}
}
And in the main
int main()
{
cout << "\n" << thereIsSimilarID("Leverpool", 1) << endl;
}
The output is 24 !!!!!
(good note that this happen just when the team (Leverpool) is the last team in the vector teamNum)
Again sorry for too much code but I need to know the bug not only fix the problem I need to learn from you
You encountered undefined behaviour.
If you take the if (teamNum[i].tName == _tname)-branch on the last element, but find no player with the correct pID, you don't return anything. Which means, that the return value is whatever random value is currently in the memory location that should hold the return value. In your case it happens to 24. But theoretically, everything could happen.
The same problem occurs when teamNum is empty.
The solution is to make sure to always return a value from a function (except if it has return type void of course):
bool thereIsSimilarID(string _tname, int _pID)
{
for (int i = 0; i < teamNum.size(); i++)
{
// In this loop return true if you find a matching element
}
// If no matching element was found we reach this point and make sure to return a value
return false;
}
You should take a look at your compiler settings and enable all the warnings. And often it's good to let it treat certain warnings as errors.

sometimes getting a segmentation fault (core dumped)

my program will sometimes run okay but sometimes it crashes in the middle of running with a segmentation fault. and the fault will come at different times each time i run the program. i debugged with gdb and found that the problem is in this function
int chooseLink(int &h, vector<Edge> &link) {
double r = 1.0*rand() / RAND_MAX;
if (link[link[h].l_ID].q == link[link[h].r_ID].q) { // this is where the error occurs
if (r<0.5)
return link[h].l_ID;
return link[h].r_ID;
}
else {
if (r < link[link[h].l_ID].q / (link[link[h].l_ID].q + link[link[h].r_ID].q))
return link[h].l_ID;
return link[h].r_ID;
}
}
my program involves calling this function millions of times. can anyone suggest what the problem may be? I'm pretty sure the vector 'link' is not going beyond its capacity. this is my first time posting a problem, so sorry if I haven't provided enough information
update
someone asked why i'm passing h by reference. i thought that passing by reference is better than passing by value because it saves space and the program will run faster. is that not correct?
someone asked for the edge class, so here it is
class Edge {
public:
int ID; // ID of edge
bool type; // true for constant, false for variable
double q; // quantity on the edge
int l_ID = 0; // ID of left edge (equals 0 if doesn't exist)
int r_ID = 0; // ID of right edge
void assignType(double &p) {
if (p == 0.5)
type = false;
else
type = true;
}
};
i added a try-catch block to the function so it looks like this:
int chooseLink(int &h, vector<Edge> &link) {
try {
if (h<0 || h>=link.size() ) {
throw h;
}
} catch(...) {
cout << "ERROR: h = " << h << endl;
}
double r = 1.0*rand() / RAND_MAX;
if (link[link[h].l_ID].q == link[link[h].r_ID].q) { // this is where the error occurs
if (r<0.5)
return link[h].l_ID;
return link[h].r_ID;
}
else {
if (r < link[link[h].l_ID].q / (link[link[h].l_ID].q + link[link[h].r_ID].q))
return link[h].l_ID;
return link[h].r_ID;
}
}
and now i don't get the segmentation fault at all. Also, the program runs fine without ever throwing an exception. what's going on? when i remove this try-catch block, i get the segfault again. i don't understand it
The first suggestion is always to boundary or range check your parameters:
int chooseLink(int h, vector<Edge> &link)
{
const unsigned int container_size = link.size();
// Check index for range.
if ((h < 0) || (h >= container.size)
{
// Report error here.
}
else
{
// More checking.
const int left_id = link[h].l_ID;
const int right_id = link[h].r_ID;
if ((left_id < 0) || (left_id >= container.size))
{
// Perform error handling
}
if ((right_id < 0) || (right_id >= container_size))
{
// Perform error handling
}
// remember to use 'const' for items that won't change.
const double r = 1.0*rand() / RAND_MAX;
if (link[left_id].q == link[right_id].q)
{
// ALWAYS use braces, even for single statements.
if (r<0.5)
{
return left_id;
}
return right_id;
}
else
{
if (r < link[left_id].q / (link[left_id].q + link[right_id].q))
{
return left_id;
}
return right_id;
}
// What does it return here?
}
}
When in doubt, range check your variables.
Also, check your logic so that all paths of execution return a value.

Error: not all control paths return a value

I am writing two functions in a program to check if a string has an assigned numeric code to its structure array or if the given numeric code has an assigned string in the same structure array. Basically, if I only know one of the two, I can get the other. I wrote the following:
int PrimaryIndex::check_title_pos(std::string title) {
bool findPos = true;
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
} else {
return -1;
}
}
std::string PrimaryIndex::check_title_at_pos(int pos) {
bool findTitle = true;
if (findTitle) {
for (int p = 1; p <= 25; p++) {
if (my_list[p].tag == pos) {
return my_list[p].title;
}
}
} else {
return "No title retrievable from " + pos;
}
}
However, it says not all control paths have a return value. I thought the else {} statement would handle that but it's not. Likewise, I added default "return -1;" and "return "";" to the appropriate functions handling int and string, respectively. That just caused it to error out.
Any idea on how I can keep this code, as I'd like to think it works but cant test it, while giving my compiler happiness? I realize through other searches that it sees conditions that could otherwise end in no returning values but theoretically, if I am right, it should work fine. :|
Thanks
In the below snippet, if s iterates to 26 without the inner if ever evaluating to true then a return statement is never reached.
if (findPos) {
for (int s = 1; s <= 25; s++) {
if (my_list[s].title == title) {
return s;
}
}
}

Segmentation fault in recursive function returning list

I have a recursive function, that is returning a list of structs.
struct Neighbour_node{
int index;
double dist;
};
And here is the function:
list<Neighbour_node> findNewNeighbours(int original, int particle, int k){
Neighbour_node node;
list<Neighbour_node> neighbours;
list<Neighbour_node> temp_neighbours;
list<Neighbour_node>::iterator iterator;
if (k <= 0){
if (particle == -1){
node.index = -1;
node.dist = 1000.0;
}
else{
node.index = particle;
node.dist = glm::length(hair[original].position - hair[particle].position);
neighbours.push_back(node);
}
}
else {
for (unsigned int i = 0; i < hair[particle].neighbours.size(); i++){
temp_neighbours = findNewNeighbours(original,hair[particle].neighbours[i],k - 1);
temp_neighbours.sort(compareNeighbour_node);
neighbours.merge(temp_neighbours,compareNeighbour_node);
}
}
return neighbours;
}
Line:
temp_neighbours = findNewNeighbours(original,hair[particle].neighbours[i],k - 1);
causes segmentation fault and I am not sure why. I have seen examples with line similar to my erroneous one and it seems, it is not wrong. But those functions were not recursive, so I am guessing that this is where the problem is - besides, when k = 0 (only one call of a function - thus as if it wasn't recursive), then it doesn't crash. Can anyone, please, help me with this?
Thanks
Check the stack size in your os.
ulimit -s
I suggest that it is because of stack.
Becase the stack you need seems increase rapidly.
Show your "hair" for more detail for us to see.

C++ Lock free producer/consumer queue

I was looking at the sample code for a lock-free queue at:
http://drdobbs.com/high-performance-computing/210604448?pgno=2
(Also reference in many SO questions such as Is there a production ready lock-free queue or hash implementation in C++)
This looks like it should work for a single producer/consumer, although there are a number of typos in the code. I've updated the code to read as shown below, but it's crashing on me. Anybody have suggestions why?
In particular, should divider and last be declared as something like:
atomic<Node *> divider, last; // shared
I don't have a compiler supporting C++0x on this machine, so perhaps that's all I need...
// Implementation from http://drdobbs.com/high-performance-computing/210604448
// Note that the code in that article (10/26/11) is broken.
// The attempted fixed version is below.
template <typename T>
class LockFreeQueue {
private:
struct Node {
Node( T val ) : value(val), next(0) { }
T value;
Node* next;
};
Node *first, // for producer only
*divider, *last; // shared
public:
LockFreeQueue()
{
first = divider = last = new Node(T()); // add dummy separator
}
~LockFreeQueue()
{
while( first != 0 ) // release the list
{
Node* tmp = first;
first = tmp->next;
delete tmp;
}
}
void Produce( const T& t )
{
last->next = new Node(t); // add the new item
last = last->next; // publish it
while (first != divider) // trim unused nodes
{
Node* tmp = first;
first = first->next;
delete tmp;
}
}
bool Consume( T& result )
{
if (divider != last) // if queue is nonempty
{
result = divider->next->value; // C: copy it back
divider = divider->next; // D: publish that we took it
return true; // and report success
}
return false; // else report empty
}
};
I wrote the following code to test this. Main (not shown) just calls TestQ().
#include "LockFreeQueue.h"
const int numThreads = 1;
std::vector<LockFreeQueue<int> > q(numThreads);
void *Solver(void *whichID)
{
int id = (long)whichID;
printf("Thread %d initialized\n", id);
int result = 0;
do {
if (q[id].Consume(result))
{
int y = 0;
for (int x = 0; x < result; x++)
{ y++; }
y = 0;
}
} while (result != -1);
return 0;
}
void TestQ()
{
std::vector<pthread_t> threads;
for (int x = 0; x < numThreads; x++)
{
pthread_t thread;
pthread_create(&thread, NULL, Solver, (void *)x);
threads.push_back(thread);
}
for (int y = 0; y < 1000000; y++)
{
for (unsigned int x = 0; x < threads.size(); x++)
{
q[x].Produce(y);
}
}
for (unsigned int x = 0; x < threads.size(); x++)
{
q[x].Produce(-1);
}
for (unsigned int x = 0; x < threads.size(); x++)
pthread_join(threads[x], 0);
}
Update: It ends up that the crash is being caused by the queue declaration:
std::vector<LockFreeQueue<int> > q(numThreads);
When I change this to be a simple array, it runs fine. (I implemented a version with locks and it was crashing too.) I see that the destructor is being called immediate after the constructor, resulting in doubly-freed memory. But, does anyone know WHY the destructor would be called immediately with a std::vector?
You'll need to make several of the pointers std::atomic, as you note, and you'll need to use compare_exchange_weak in a loop to update them atomically. Otherwise, multiple consumers might consume the same node and multiple producers might corrupt the list.
It's critically important that these writes (just one example from your code) occur in order:
last->next = new Node(t); // add the new item
last = last->next; // publish it
That's not guaranteed by C++ -- the optimizer can rearrange things however it likes, as long as the current thread always acts as-if the program ran exactly the way you wrote it. And then the CPU cache can come along and reorder things further.
You need memory fences. Making the pointers use the atomic type should have that effect.
This could be totally off the mark, but I can't help but wonder whether you're having some sort of static initialization related issue... For laughs, try declaring q as a pointer to a vector of lock-free queues and allocating it on the heap in main().