So to start off this code works on all my redhat machines and some other solaris machines. The machine that is producing the fault is a solaris 64 bit. The code I have is as follows:
This is the frUUID class:
frUUID::frUUID()
{}
std::string frUUID::genUUID()
{
char uuidBuff[36];
uuid_t uuidGenerated;
uuid_generate_random(uuidGenerated);
uuid_unparse(uuidGenerated, uuidBuff);
std::cout << uuidBuff << std::endl; // prints out a correct uuid
return std::string(uuidBuff);
}
Then in a unit test I have:
frUUID uuids;
std::string uuid1 = uuids.genUUID();
std::cout << std::endl << "UUID 1: " << uuid1 << std::endl;
//This cout produces the seg fault on the uuid1
I have no idea what is going on here everything seems to be correct? Does anyone have any ideas?
From the uuid_unparse man page:
The uuid_unparse function converts the supplied UUID uu from the internal binary format into a 36-byte string (plus tailing '\0')
Your buffer is too small for that. You're in undefined behavior territory.
You're not leaving space for the trailing null byte in uuidBuff.
change
char uuidBuff[36];
to
char uuidBuff[37];
for the null character
Related
I'm using Visual Studio 2019: why does this command do nothing?
std::cout << unsigned char(133);
It literally gets skipped by my compiler (I verified it using step-by-step debug):
I expected a print of à.
Every output before the next command is ignored, but not the previous ones. (std::cout << "12" << unsigned char(133) << "34"; prints "12")
I've also tried to change it to these:
std::cout << unsigned char(133) << std::flush;
std::cout << (unsigned char)(133);
std::cout << char(-123);
but the result is the same.
I remember that it worked before, and some of my programs that use this command have misteriously stopped working... In a blank new project same result!
I thought that it my new custom keyboard layout could be the cause, but disabling it does not change so much.
On other online compilers it works properly, so may it be a bug of Visual Studio 2019?
The "sane" answer is: don't rely on extended-ASCII characters. Unicode is widespread enough to make this the preferred approach:
#include <iostream>
int main() {
std::cout << u8"\u00e0\n";
}
This will explicitly print the character à you requested; in fact, that's also how your browser understands it, which you can easily verify by putting into e.g. some unicode character search, which will result in LATIN SMALL LETTER A WITH GRAVE, with the code U+00E0 which you can spot in the code above.
In your example, there's no difference between using a signed or unsigned char; the byte value 133 gets written to the terminal, but the way it interprets it might differ from machine to machine, basing on how it's actually set up to interpret it. In fact, in a UTF-8 console, this is simply a wrong unicode sequence (u"\0x85" isn't a valid character) - if your OS was switched to UTF-8, that might be why you're seeing no output.
You can try to use static_cast
std::cout << static_cast<unsigned char>(133) << std::endl;
Or
std::cout << static_cast<char>(133) << std::endl;
Since in mine all of this is working, it's hard to pinpoint the problem, the common sense would point to some configuration issue.
I use the following code to convert the string into the integers:
int main(){
const char* mystring="abcdefghijklmnop";
unsigned int* key = (unsigned int*)mystring;
for(int i=0;i<2;i++) {
std::cout << i << ": " << key[i] << std::endl;
}
std::cout << std::endl << "Result for:" << mystring << std::endl;
}
Result:
0: 1684234849
1: 1751606885
2: 1818978921
3: 1886350957
Result for:abcdefghijklmnop
As you can see, its working really fine, but just until the moment when the encoding is different, eg. for the string like: ®_ďÚ.J.®—Mf3Lý!® (ASCII) (see the Result for: below)
It returns:
0: 3294604994
1: 781894543
2: 2931961418
3: 1301577954
Result for:®_ÄŹĂš.J.®—Mf3LĂ˝!® // <-- notice this, its totally different as the input (`®_ďÚ.J.®—Mf3Lý!®`)
I was trying setting the encoding in my IDE (Netbeans) but without any possitive results, also I was trying to compile to source on ideone.com, setting the browser encoding - unfortunately with the same results. Is there any possibility for it to generate the real result based on the input string encoding without messing it up? Maybe there are any other possibilities to achieve what I want?
Your IDE is entering the characters encoded as UTF-8. I verified this by working backwards from your numeric output, it produced ®_ďÚ.J.®—M. By the way, calling that ASCII is not accurate at all.
Your output window is using a different encoding. By the looks of it it's code page 1250 Central/Eastern European.
Hi I am facing memory fault with my code. I used gdb and found out where memory fault occurs. But I am not able to solve that. The lines of code where memory fault occurs is below. Please help me friends.
void CJob::print_parm_file(){
int m_nFuncid;
CCmdset* pCmdset = NULL;
const int size=1024;
char fname[80];
char dbg_buf[size]="";
unsigned int i, gotit=0;
for (i=0; i < entries(); i++)
{
pCmdset = (CCmdset*) at(i);
//RWCollectableString *cmdset = (RWCollectableString *)pCmdset->at(0);
//RWCString m_Function=cmdset->data();
CXmlobj *xobj = (CXmlobj *)pCmdset->at(0);
cout <<"The value of m_name.data() //segfault issue is : " << xobj->m_name << endl;
cout <<"The value of m_name.data() //segfault issue is : " << xobj->m_name.data() << endl;
RWCString m_Function=xobj->m_name.data(); //segmentation fault occurs in this line
I have printed the value of m_name.data() to check its value. when i tried printing its value, segmentation fault occured in cout statements itself.
NOTE : This issue is happening only in Linux server. The code is working perfect in Unix server without any issue.
Please help me ! Thanks !!!
My educated guess is that m_name is of type std::string. There is no guarantee that a null character terminates the character sequence pointed by the value returned by data(). Simply put, your prints may access more elements than that string actually contains which causes this segmentation fault.
Try adding a \0 character at the end of the string, or replace data() with c_str() which is guaranteed to be null-terminated.
Did you first establish that xobj is valid?
CXmlobj *xobj = (CXmlobj *)pCmdset->at(0); // if xobj is invalid
xobj->m_name.data(); // ... then this will invoke undefined behavior
The simplest thing to try is just assign that string variable to a temporary string variable and see what happens. If you still get a segmentation fault, then the problem is more than likely that xobj is not pointing to a valid CXmlobj.
I met a strange problem when trying to get the result of a string’s function c_str() whose result is inconsistent with g++.
There is a function called Test to return a string instance. And I want to use a char* type to store the result (it’s needed). As you can see the function is simple return a string “resultstring”. But when I try to get the result something strange happened.
The result I got is “” in part two. The part one and part three both return the “resultstring”. While that’s in Visual Studio. The three part of the same code compiled with g++ both return the “result string. Let’s just as well see the result first:
result of vs:
address:16841988
resultstring
address:16842096
"here is a empty line"
address:16842060
address:16842144
address:16842396
address:16842396
resultstring
result of g++
address:5705156
resultstring
address:5705156
resultstring
address:5705156
address:5705196
address:5705156
address:5705156
resultstring
The code is very simple list below:
#include <iostream>
#include <string>
using namespace std;
string Test()
{
char a[64] = "resultstring";
return string(a);
}
int main(void)
{
//part one
cout << "address:"<< (unsigned)Test().c_str() << endl;
cout << Test().c_str() << endl;
//part two
char *j = const_cast<char*>(Test().c_str());
cout << "address:"<< (unsigned)Test().c_str() << endl;
cout << j << endl;
cout << "address:" << (unsigned)j <<endl;
//part three
string h3 = Test();
char* j2 = const_cast<char*>(h3.c_str());
cout << "address:"<< (unsigned)Test().c_str() << endl;
cout << "address:"<< (unsigned)h3.c_str() << endl;
cout << "address:" << (unsigned)j2 <<endl;
cout << j2 <<endl;
getchar();
return 0;
}
Now I have three questions.
1st, why the result complied by g++ returns all resultstring while the result of Visual Studio returns all resultstring except for variable j? If you debug into this you’ll find that VC++ only set the address of j2 like 00 65 73 75 … which is esultstring with a 00 begin address. And it is not strange that we’ll get “”. It’s just like char* str = "\0something else" you’ll always get "". But the question is why does this happen only with j?
2nd, why does one of the addresses of the (unsigned) Test ().c_str() is different with others? If we remove the line string h3 = Test () the address will be all the same.
3rd, Is it the “correct” behavior of Visual Studio returning “” value of variable j? why it is different with g++?
Looking forward to your replies.
Regards,
Kevin
This is totally flawed. You create and destroy a temporary string every time you call Test(). Any attempt to access memory using pointer returned by Test().c_str() after temporary was destroyed makes no sense - memory was freed already. It MIGHT have the old values (if nothing is written there before the access), but it might have anything as well (if it is reused before the access). It's Undefined Behavior.
In case of VC++ it is overwritten once and is not in other cases. With GCC - it's never overwritten. But this is pure chance. Once again - it's UB.
You have undefined behavior. The std::string returned by Test() is a temporary and the pointer returned by c_str() (stored in j) is no longer valid after the lifetime of the temporary ends. This means that anything can happen. The array the pointer points to may contain garbage, it may be the original string or the implementation may have null terminated the beginning of it. Accessing it may cause a segmentation fault or it may allow you to access the original string data. This can and usually does vary between different compilers and implementations of the standard library.
char *j = const_cast<char*>(Test().c_str());
// The contents pointed to by j are no longer valid and access that content
// is undefined behavior
cout << "address:"<< (unsigned)Test().c_str() << endl;
The address is different between calls to Test() because it returns a temporary each time you call it. Some compilers may optimize this and/or the allocation of data may get the same block of memory but it is not guaranteed to be the same.
I am trying to get a double to be a string through stringstream, but it is not working.
std::string MatlabPlotter::getTimeVector( unsigned int xvector_size, double ts ){
std::string tv;
ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
It outputs only "0:" on my console...
I'm working on two projects, both with the same problem. I'm posting a different one, which runs into the same problem. It is posted here:
http://pastebin.com/m2dd76a63
I have three classes PolyClass.h and .cpp, and the main. The function with the problem is PrintPoly. Can someone help me out? Thanks a bunch!!
You're printing correctly, however your logic in the order of printing is incorrect.
I modified it to work they way I think you wanted it to, let me know if this helps.
http://pastebin.com/d3e6e8263
Old answer:
Your code works, though ostringstream is in the std namespace. The problem is in your file printing code.
Can I see your call to the function?
I made a test case:
// #include necessary headers
int main(void)
{
std::string s;
s = MatlabPlotter::getTimeVector(1,1.0);
}
The output I get is 0:1:1
The following code is 100% correct:
#include <iostream>
#include <sstream>
#include <string>
// removed MatlabPlotter namespace, should have no effect
std::string getTimeVector(unsigned int xvector_size, double ts)
{
// std::string tv; // not needed
std::ostringstream ss;
ss << "0:" << ts << ":" << xvector_size;
std::cout << ss.str() << std::endl;
return ss.str();
}
int main(void)
{
// all work
// 1:
getTimeVector(0, 3.1415);
// 2: (note, prints twice, once in the function, once outside)
std::cout << getTimeVector(0, 3.1415) << std::endl;
// 3: (note, prints twice, once in the function, once outside)
std::string r = getTimeVector(0, 3.1415);
std::cout << r << std::endl;
}
Find where we differ, that's likely your source of error. Because it stops at your double, I'm guessing the double you're trying to print is infinity, NaN (not a number), or some other error state.
I can't really help with the "no output" part of this, as you didn't show your code that tries to output this. As a guess, did you perhaps not put an EOL in there somehow? Some systems won't give any text output until they hit a newline. You can do this by tacking a << std::endl onto your line, or a '\n' to your string.
Since you didn't put down a using for it, you need to use the type std::ostringstream. This is similar to how you had to use "std:string" instead of just "string".
Also, were it me, I'd get rid of that temp variable and just return ss.str(); It is less code (to possibly get wrong), and probabaly less work for the program.
Well, I tried the code you linked to and it outputs
B 4
A 5
B 4
C 3
x^ + 5x^ + 3
for me before crashing although the crash happens after PrintPoly. From looking at the code this is what I'd expect it to print. Are you saying you get no integers appearing after the letters?
Thanks all for your input! Not sure of the exact error, but it must be some setting in XCode which is messing it up. I made a CMakeLists.txt file and compiled it from the terminal using
cmake -G XCode ..
and produced an XCode project. I ran it, and now it works fine...now would anyone happen to know what might cause XCode to do this? I'm running version 3.2 with the following:
64-bit
Component versions
Xcode IDE: 1610.0
Xcode Core: 1608.0
ToolSupport: 1591.0