Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"We received the following error when we ran your code:" but no error is following #2199

Open
bakaiadam opened this issue Jun 14, 2022 · 2 comments

Comments

@bakaiadam
Copy link

bakaiadam commented Jun 14, 2022

I'm on the site: https://exercism.org/tracks/cpp/exercises/circular-buffer/edit

My .hh source code is:

#if !defined(CIRCULAR_BUFFER_H)
#define CIRCULAR_BUFFER_H
#include <vector>
#include  <stdexcept>
using namespace std;
namespace circular_buffer {
template<typename T>
class  circular_buffer
{

public:
int pos=0;
int writepos=0;
int len=0;
vector<T> elems;
int num;
circular_buffer(int num): elems(num)
{
    num=num;
}





T read()
{
    if (len==0)
        throw domain_error("alma");
    len--;
    T ret= elems[pos];
    pos=(pos+1)%num;
    return ret;
    
}

void write(T a)
{
    if (len==num)
        throw domain_error("alma");
    len++;
 
    
    writepos=(writepos+1)%num;
    elems[writepos]=a;
    
    
}

void clear()
{
    len=0;
    
}

void overwrite(T a)
{
       if (len==num)
       {}
    else
    len++;
 
    
    writepos=(writepos+1)%num;
    elems[writepos]=a;

    
}


};

}  // namespace circular_buffer

#endif // CIRCULAR_BUFFER_H

The .cc source code is the default

@siebenschlaefer
Copy link

I don't know why the website reported an error but didn't show it.

But maybe I can help with the code. Look at the constructor. In the function body it assigns num = num;. That doesn't work, officially it reads an uninitialized member variable num (invoking undefined behavior), but in practice that statement will probably do nothing, and num still has an "indeterminate value".
Instead initialize num in the "member initializer list", just like elems: : elems(num), num{num} { } In that context the first num in num{num} refers to the member variable, the second one to the parameter.

@bakaiadam
Copy link
Author

thank you. with your help, i managed to solve the exercise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants