I have a simple code which is basically like the one below:
static std::string const part1[] = {"Test1", "Test2", "Test3"};
static std::string const part2[] = {"Pass", "Fail", "Retry"};
std::string test = part1[1] + part2[0];
I have included the string which in turn has the basic_string.h. I know that there is an overloaded +operator there.
When I built this I got no errors but when I tried to run it, I got a segmentation error.
The problem I noticed later is that if I simply try to print the array elements, I am seeing the same segmentation error.
I don't see where the memory leak is happening. Any clues?
In c++ array declaration is not possible in the way you used in your code.
A Valid code example is
static std::string const part1[] ={"Test1", "Test2", "Test3"};
static std::string const part2[] = {"Pass", "Fail", "Retry"};
std::string test = part1[1] + part2[0];
Related
since yesterday I have been struggling to turn text into label with code from another class, I came to this:
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
TestApp::UI_Error form("test", "test");
Application::Run(% form);
Using the above code, i display a winapi form that receives "test", "test" as 2x const char* on loading, the problem appears when im trying to set the text in labels using these variables
The code looks like this:
public:
UI_Error(const char* errorText, const char* errorCode)
{
InitializeComponent();
this->testLabel->Text = System::Convert::ToString(errorText);
}
For some reason, each time the return value shown in the win forms window is "true", although it should be "test" here, does anyone know the solution?
I tried to use std::string instead of const char*, unfortunately for some reason i get the error code that a static variable is required :(
Maybe I am wrong here, but System::Convert::ToString() seems not to have a method that accepts a const char* pointer. It looks like it gets cast to something else.
Try this instead:
Text = gcnew System::String(errorText);
I have written a small wrapper for typeinfo to get the typecode of a variable at compile time more easily:
template<typename DataType>
class TypeInfo
{
public:
static const char* typecode()
{
DataType TypedVariable = 0;
const char* code = typeid(TypedVariable).name();
return(code);
};
};
I use it like this:
const char* code = TypeInfo<float>::typecode();
It compiles perfectly fine and works as expected, but I am getting the warning
src/common.hh(153): warning: variable "TypedVariable" was set but never used
detected during:
instantiation of "char TypeInfo<DataType>::typecode() [with DataType=r32]"
...
I am wondering why "calling" typeid() on a variable does not count as using it. I know that it is a defined keyword, but still I am irritated that getting the type of a variable does not count as using it.
The compilation is done using nvcc of CUDA 9.2. Maybe it is a CUDA specific thing?
Thanks for any help :)
//edit:
I made a mistake by not returning the full char* because I use only normal types! Thanks for making me aware of the typo! I also added the template definition. I forgot to copy that over!
Because you don't use the value of TypedVariable. You just use its type (and you can get it's type by rewriting your initialization as:
char const * const code = typeid(DataType).name();
I have an assignment where i was given c++ code that has multiple test functions, and i have to write the stri class with all the functions necesary for these tests to pass. I am having difficulty with one particular test about chain linking.
void Lab4Tests::testChainedSet() {
stri greet = "Hello";
assert(0==strcmp("Hello", greet.get()), "testChainedSet", "internal representation error");
greet.set("Hi").set("Buna");
assert(0==strcmp("Buna", greet.get()), "testChainedSet", "set failed");
}
My function inside the class that I wrote to solve this test is the following
char* set(const char* s){
len=strlen(s);
repres=new char(len+1);
strcpy(repres,s);
return repres;
}
I get an error when compiling the code
error: request for member 'set' in 'greet.stri::set(((const char*)"Hi"))', which is of non-class type 'char*'|
I dont understand chain linking that well, I would appreciate if somebody could point out what I'm doing wrong. Thanks in advance!
If you want to be able to chain calls you need to return a reference to the this object.
For instance
stri& set(const char* s)
{
repres = std::strdup(s);
return *this;
}
I've taken the liberty of simplifying your string duplication. I haven't fixed the memory leak that you will get if you call set when repres already contains dynamically allocated memory.
I have some code that looks like this:
static std::string Foo(const std::string& blah)
{
if ( someWierdEdgeCase() ){
return false; // <-- this line has a compiler error
}
std::string resourcePath;
resourcePath.append("/assets/");
return resourcePath;
}
It used to compile fine, but then I upgraded to Xcode 5.1, and now it no longer compiles. The error I get is the following one:
No viable conversion from 'bool' to 'std::string'
I would like to know what I should replace 'return false' with so that this works the way it used to.
Normally, I would be happy to return something other than false, and clearly that is not good behavior. But somehow this code used to compile and run, and I want to understand what it was doing, in case some other part of this codebase is relying on what is certainly weird behavior.
This:
return false; // <-- this line has a compiler error
There is no standard way to convert bool to std::string (please correct me if there is or was something special in gcc (the old XCode mac compiler)). This means that your code base used to contain explicit code to convert the bool to string.
If it is not compiling now this suggests this conversion was removed from your code base.
A couple of people of suggested alternatives. But I doubt any of these are going to work. As the old code had a depedency on how it used to work. So making any specific recomendation will depend on working out how the old code compiled and what it returned when someWierdEdgeCase() is true. Basically you need to replicate this behavior.
Otherwise you need to hunt down all used cases in your code and change the behavior to match the new behavior. In this case I would change the name of the function. Re-Compile and see where the code breaks and check the behavior at each location and make sure it behaves the same.
static std::string Foo(const std::string& blah)
{
std::string resourcePath = "";
if ( someWierdEdgeCase() ){
return resourcePath; // <-- Now you're returning a string
}
resourcePath.append("/assets/");
return resourcePath;
}
If you need the return type to be - for whatever reason - not always present, return by pointer, instead of returning by value.
static yourType* Foo(const std::string& blah){
if ( someWierdEdgeCase() ){
return 0;
}
}
Then you can test and assign the function in the same line
yourType* result;
if(result = Foo("something")){
// the result was correct
Of course - since your function returns a std::string, you can return an empty string (""), or - also independent of the return type - throw an exception.
I had same issue that with the fact that my interface file and implementation file were using different data types in method declaration.Putting same data type on both place in method declaration error went away.
I asked a similar question a couple of days ago, but I'm looking for more insight. I'm getting an AccessViolationException when I add a string to my program:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at _cexit()
at <CrtImplementationDetails>.LanguageSupport._UninitializeDefaultDomain(Void * cookie)
at <CrtImplementationDetails>.LanguageSupport.UninitializeDefaultDomain()
at <CrtImplementationDetails>.LanguageSupport.DomainUnload(Object source, EventArgs arguments)
at <CrtImplementationDetails>.ModuleUninitializer.SingletonDomainUnload(Object source, EventArgs arguments)
The program has a bunch of const std::string's at the top level:
const std::string caseDelimitedOption = "CaseDelimited";
const std::string endOfLineOption = "EndOfLine";
const std::string functionNameDelimitWordsOption = "FunctionNameDelimitWords";
const std::string functionNameStartCaseOption = "FunctionNameStartCase";
const std::string indentStringOption = "IndentString";
const std::string lowerCaseOption = "LowerCase";
const std::string newLineBetweenDoAndWhileOption = "NewLineBetweenDoAndWhile";
const std::string nextLineOption = "NextLine";
const std::string nextLineAsWellAsCloseParenOption = "NextLineAsWellAsCloseParen";
const std::string noBracesAroundSingleStatementBlockOption = "NoBracesAroundSingleStatementBlock";
const std::string openBraceLocationOption = "OpenBraceLocation";
const std::string underscoreDelimitedOption = "UnderscoreDelimited";
const std::string upperCaseOption = "UpperCase";
const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment";
If I replace last string with:
const std::string whiteSpaceBeforeLeadingCmntOption = ""; //"WhiteSpaceBeforeLeadingComment";
then the exception goes away. Is this just extra memory (from the string) hitting some bad memory that was caused elsewhere in my program? Or is the exception related to the string?
Thanks for any help,
Joe
I assume these strings are global variables.
Are you trying to access these strings from the constructor of another global variable (or from some method that is called before main is entered)?
If this is the case you are suffering from the probelem that global variable initialization order is undefined across multiple compilation units. There are a few solutions but more information about your application would probably be useful.
First test to see if main is even entered.
I would think that it working with the empty string is the result of some compiler optimization trick.
Try
valgrind --leak-check=full your.exe
and remember to compile your application with -g to get source code line in the executable.
The problem isn't the string. Somewhere in your program, you're reading or writing out of bounds. This results in undefined behavior, meaning that the program might appear to run, you might get an access violation, or it might crash with another error, or... anything else might happen.
The reason the string appears to make a difference is simply that it changes the program subtly, causing the out-of-bounds access to reach an unallocated page.