Reputation: 1399
Im trying to build this for the amd64arch and it keeps giving me segmentation fault:
#include "client.h"
namespace {
class SimpleClientImpl : public SimpleClient {
private:
int progress_counter_;
public:
SimpleClientImpl() : progress_counter_(0) {}
int GetProgress() const;
char* CutPrefix(char* data);
};
int SimpleClientImpl::GetProgress() const {
return progress_counter_;
}
char* SimpleClientImpl::CutPrefix(char* data) {
progress_counter_++;
return data + *reinterpret_cast<size_t*>(data) + sizeof(size_t);
}
} // namespace
std::shared_ptr<SimpleClient> CreateSimpleClient() {
return std::shared_ptr<SimpleClient>(new SimpleClientImpl);
}
In the client.h I got:
#ifndef TEST_CLIENT_H_
#define TEST_CLIENT_H_
#include <memory>
class SimpleClient {
public:
virtual int GetProgress() const = 0;
virtual char* CutPrefix(char* data) = 0;
virtual ~SimpleClient() {}
};
std::shared_ptr<SimpleClient> CreateSimpleClient();
#endif
Any Idea of how can i fix this? I'm not sure why would it give me a segmentation fault, i've tryed runnin it as admin, but I dont really get where is the problem.
Upvotes: 0
Views: 164
Reputation: 2085
char* CutPrefix(char* data);
You may never allocate memory for that pointer on string (Either with new or the c malloc) ;
My guess is that you miswrote this line :
return data + *reinterpret_cast<size_t*>(data) + sizeof(size_t);
And that you should either work with strings
, or do your allocation correctly beforehands if you really want to keep working with char* in cpp.
Upvotes: 1
Reputation: 36617
Although you haven't shown calling code, it is presumably creating a SimpleClientImpl
and passing (the address of) some character buffer to the CutPrefix()
member function. Possibly repeatedly.
Check the data that is being supplied to CutPrefix()
. Either it is not encoded in the form you assume (a length, followed by that number of characters) or the caller is walking past the end of the supplied buffer. Possibly both.
In either case, the caller will exhibit undefined behaviour if it uses the pointer returned.
Since you haven't provided the calling code, however, it is not possible to advise on how to fix the problem.
Upvotes: 0