So I've been trying to convert integer values to wchar_t*. This is the test I run so I could simplify it as much as I can.
int test=123;
wchar_t *testc[12][12];testc[0][0]=L"hello";
_itow(test,testc[0][0],10);
wcout<<testc[0][0];
This code right here compiles but also gives me the Not Responding error of doom.
What is VERY strange for my understanding is why this
int test=123;
wchar_t *testc[12][12];testc[0][0]=L"hello";
_itow(test,testc[1][0],10);
wcout<<testc[0][0]<<testc[1][0];
Works without any problem, and showing the output "hello123" just as intended.
Any idea why this happens?
My project has some occurrences similar to the first code shown (except the wcout part), thus I want to understand why they give me the Not Responding state.
Main issue with your code is not allocating memory for testc[1][0].
Also it will be better to use standard c++ functions like std::to_wstring instead of _itow.
So here is sample code for your problem :
int main()
{
int test=123;
wchar_t *testc[12][12];
testc[0][0]=L"hello";
testc[1][0] = new wchar_t[4];
std::wstring temp = std::to_wstring(123);
for(int i=0;i<temp.length();i++)
{
testc[1][0][i] = temp[i];
}
wcout<<testc[0][0]<<testc[1][0];
return 0;
}
This is just sample code and i am assuming in your program you are taking care of memory allocation and deallocation
Related
I' m trying to understad the work with a pointers. So I've wrote a test program where name is split into labels by removing the separating dots. Each label is represented as a length/data pair as follows:
google.ru represents as "x\06googlex\02ru"
I get signal SIGABRT when i returned from my test function
I guess it's caused with my bad work with pointer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void test(unsigned char* dns, unsigned char* host);
int main(int argc, const char * argv[])
{
unsigned char host[]="google.ru";
unsigned char* dnsTest=(unsigned char*)malloc(20);
if(dnsTest==NULL)
{
exit(1);
}
test(dnsTest, host);
printf("%s", dnsTest);
free(dnsTest);
return 0;
}
void test(unsigned char* dns, unsigned char* host)
{
strcat((char*)host, ".");
int lock=0;
for(int i=0; i<strlen((char *)host);i++)
{
if(host[i]=='.')
{
*dns=i-lock;
dns++;
for(;lock<i; lock++)
{
*dns=host[lock];
dns++;
}
lock++;
}
}
*dns='\0';
}
Since you tagged c++ as well, you can use new \ delete instead of malloc \ free. New will call constructor (when you will learn classes it will be useful), and new return to you exact type, so no need to cast (and casting is almost always a bad idea)
Then assertion after memory allocation with new will be redundant:
if(dnsTest==NULL)
since c++ new will throw an exception by default.
If you go ahead, you can use std::string - its much more simple than c null terminated strings (but not for the task of understanding pointers).
Every other comments (about redundant strlen usage and absence of '\0' symbol) is correct too, but I want to give you two advices, how to grasp pointers.
First - read K&R - it's the Bible.
Second - if you use Microsoft Visual Studio, you can compile your code in Debug mode, and use Memory View tab. Visual Studio compiler place some magic number inside memory (link) at debug mode. They can help you with understanding where you addressing unallocated memory or how exactly your memory layout looks like.
I'm quite new to C++ and I have to implement a Polybius cipher function.
I passed a char c-array as a parameter to my function.
I used a dummy string of "PROG" to test the code and it works perfectly when I compile it in x64(which was set as default by Visual Studio 2015 for some reason). However if I pass the array to the function in a x86 build, it contains weird characters for no appearant reason:
"PROG\x190§ÎæÏX1"
Heres my code:
void createPolybiusMatrix(const char keyphrase[]) {
//Keyphrase contains "PROG" on x64 but "PROG\x190§ÎæÏX1" on x86!
//Do Stuff
}
int main() {
char passphrase[] = {'P','R','O','G'};
//Everythings fine here, passphrase contains "PROG" on both platforms.
createPolybiusMatrix(passphrase);
return 0;
}
Any ideas? I'm still quite new to C++ and this confuses me like hell!?
C strings need to be null-terminated. In order for your program to work correctly, you need to use:
char passphrase[] = {'P','R','O','G','\0'};
The char array is not null-terminated, so if the byte following 'G' is not 0, you'll overflow and print out garbage. This is technically undefined behavior.
To print the char array as you would a string, you need to null-terminate it.
I have C++ code that is built with gcc (4.1.2) with -O2.
When this code is compiled and run with no optimisation, the program executes without any issue.
When compiled with O1/O2/O3, the code will crash with a valgrind indicating an invalid free.
This has been narrowed to the string variables inside the function.
The code will read in a file, and will iterate the contents.
I have removed all processing code, and the following code snippet causes the core...
int MyParser::iParseConfig(Config &inConfig)
{
bool keepGoing = true;
while(keepGoing)
{
string valueKey = "";
keepGoing = false;
}
return 0;
}
When this is run with non-optimised, it works fine.
When I build and run this optimised, it will not work.
It looks to be an issue with the way GCC optimises the string class.
Any ideas how we can circumvent this?
If you are overflowing the charIndex, (when i gets higher than 99) who knows what your program state is in... the storage you declare is not very big (2 chars and a null).
I cannot explain why exactly this code crashes for you when compiled with optimizations, perhaps i gets more than 2 digits and you have a buffer overflow, maybe it's something different, but anyway I would change the code:
sprintf(charIndex, "%d", i++);
string valueKey = "";
valueKey.append("Value").append(charIndex);
string value = inConfig.sFindField(valueKey);
like this:
stringstream ss;
ss << "Value" << i++;
string value(ss.str());
It is more C++-like and should work. Try it.
If you are curious if this is really a buffer overflow situation, insert the line:
assert(i < 99);
before the call to printf. Or use snprintf:
snprintf(charIndex, sizeof(charIndex), "%d", i++);
Or make your buffer bigger.
This was an issue with header files being incorrectly included - there was a duplicate include of the MyParser.h file in the list of includes.
This caused some strange scenario around the string optimisation within the GCC optimisation levels.
I am having trouble trying to figure how why my g++ compiled program seg faults at a strncat() call.
I've been jumping around this site and general Googling and found a number of similar problems but haven't found any solutions that work for me. This is part of a much larger code and there's only so much I can do to redefine variables as the code isn't mine.
All this section of the code is meant to do is read in the last line of a file, remove the relevant data and concatenate to a char*
When I run it, I get a segmentation fault at the line with strncat(RAM,nextchar,1)
char line[256]={"0"};
char nextchar[10]={"0"};
int length=0;
double rac;
double decc;
bool SPACE=false;
char * RAM="RA: ";
char * DECM="DEC: ";
if(AutoColData.good()){
while(!AutoColData.eof()) AutoColData.getline(line,256);
for(int i=0;i<strlen(line);i++){
nextchar[0]=line[i];
cout<<line[i];
if(isspace(nextchar[0])&& !SPACE) SPACE=!SPACE;
else if(SPACE && !isspace(nextchar[0])){
SPACE=!SPACE;
length++;
}
if(length==6) {
cout<<"\n"<<RAM<<nextchar<<"\n";
strncat(RAM,nextchar,1);
}
else if(length==7) strcat(DECM,nextchar);
}
}
There are some sloppy choices here, I know (the whole "SPACE" thing is messy). But I don't see any reason for this to Seg Fault. It runs fine up until the line with strncat(). The cout works fine, both strings print and have the right data in them but then strncat fails. I've tried using malloc(), strings and nothing seems to work. If anyone could point out what stupid thing I'm doing, it would be very helpful. Thank you.
RAM is wrongly declared as a char *, when it really should be a const char *: String literals are read-only, and you are not allowed to write to them. Your strncat call is simply undefined behaviour.
If you want a writable string, you could make a large enough char array: char RAM[100] = "RA: "; (this will be zero-padded at the back), or better even, just use std::string:
std::string RAM = "RA: ";
RAM += nextchar;
Hey everyone, thanks for taking the time to address my problem. I've looked at so much material at this point that I've just started getting more and more confused. Basically, I'm writing a simple segment of code that parses a string. Please understand that my question is NOT about parsing. I am using C++ and have never used C before and possess a little bit of c++ experience (introductory experience, I'm still a newbie).
struct parsedString{
char chunk1[50];
char chunk2[10];
char chunk3[50];
};
main(char* bigstring)
{
parsedString ps;
ps = parseMe(bigString)
cout << ps.chunk1 << endl;
cout << ps.chunk2 << endl;
cout << ps.chunk3 << endl;
}
parsedString parseMe(char* stringToParse)
{
char* parseStr = stringToParse;
parsedString ps;
ps.chunk1 = first x chars;
ps.chunk2 = next y chars;
ps.chunk3 = last z chars;
return ps;
}
Obviously this is not working code, I didn't want to throw up all the extra stuff since it would be tougher to read through and I'm pretty sure my problem is a newbie c/c++ problem and something about memory allocation or something like that...
Basically when the main function gets to printing the strings from the parsedString it prints out exactly what I want it to, plus garbage characters. I'm entering the values for each array ps.chunk using
ps.chunk1[i] = *parseStr
since parseStr gets me each individual character. I can't figure out where the garbage characters are coming from, does it have something to do with how I am accessing the big string? Originally I used char in the struct instead of arrays and when I printed from within the parseMe() function they would come out great but they would turn into gibberish when I accessed it from the main function. Any help is appreciated, thanks so much.
If something is unclear please let me know I'll do my best to elaborate.
It's not clear why you're trying to do this with '\0' terminated
strings, when C++ has a perfectly usable string class, but
supposing some pedagogical reasons: are your strings '\0'
terminated? How do you extract and copy the first x chars into
ps.chunk1? How do you ensure that it has a '\0'?
If you really want to get exactly n characters, you have to:
assert(strlen(parseStr) >= n);
, copy them into the target (which must contain at least n+1 char's),
memcpy(ps.chunk1, parseStr, n);
, and add the final '\0':
ps.chunk1[n] = '\0';
(And, of course, advance parseStr: parseStr += n;)
Or you can simply use std::string everywhere, and write
something like:
ps.chunk1(stringToParse.substr(startPosition, length));
As pointed out by others, you should use std::string to represent strings, and save yourself all the trouble. This could look like this:
struct parsedString{
std::string chunk1;
std::string chunk2;
std::string chunk3;
};
parsedString parseMe(const std::stirng & stringToParse) {
parsedString result;
// just an example - this assigns the first two characters of stringToParse
// to chunk1
result.chunk1 = stringToParse.substr(0, 2);
// get the other chunks
return result; // return the result
}
The above code should illustrate the usage. You can find more information on std::string here.
This could be happening due to a couple of reasons.
When you declare parsedString ps; it would be good to initialize the structure and make sure that you are receiving clean memory blocks to work with.parsedString ps = {0}; Some platforms don't do this and it's up to you to zero the memory before using it.
char* strings must end with the \0 character. This character signals the end of a char*. This is mandatory! Not inserting it at the end of the string will most probably make the print operation (for instance) display contents beyond the limits of the array giving you garbage characters. This is automatically achieved by zeroing all the struct as I suggest above.