|
-
Sep 23rd, 2002, 04:59 PM
#1
Thread Starter
Frenzied Member
segmentation fault on strcat
I have this code:
Code:
#include <string>
#include <iostream>
using namespace std;
void main() {
char* sztest = "hello";
char* retVal = "";
retVal = strcat(retVal,sztest);
cout << retVal << endl;
}
Compiling using 'g++ test.cpp'
I run it and get segmentation fault that comes from the strcat.
Now whats wrong with this code?
retired member. Thanks for everything 
-
Sep 23rd, 2002, 05:11 PM
#2
Frenzied Member
Its retVal.
Code:
#include <string>
#include <iostream>
using namespace std;
void main() {
char* sztest = "hello";
char* retVal = new char[128];
retVal[0] = 0;
retVal = strcat(retVal,sztest);
cout << retVal << endl;
delete retVal;
}
strcat was attempting to write past the end of retVal, which was 1 byte long. Bad idea =).
Z.
-
Sep 23rd, 2002, 05:13 PM
#3
Monday Morning Lunatic
Code:
#include <string>
#include <iostream>
using namespace std;
void main() {
char* sztest = "hello";
char* retVal = "";
retVal = strcat(retVal,sztest);
cout << retVal << endl;
}
What you have here is two pointer values, pointing at two separate, fixed-size, unmodifiable strings. The compiler should give a warning that they need to be const char*. Try the -Wall switch to g++.
Anyway, in C++ what you should do is:
Code:
#include <string>
#include <iostream>
using namespace std;
void main() {
string test("Hello");
string retVal("World");
test += " ";
test = test + retVal;
cout << test << endl;
}
...or something similar using the string class
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Sep 23rd, 2002, 05:43 PM
#4
Thread Starter
Frenzied Member
thanks but now how do I change it back to a char* so I can return it?
return (char*)test;
^doesnt work^
retired member. Thanks for everything 
-
Sep 23rd, 2002, 05:48 PM
#5
Monday Morning Lunatic
You can't return a pointer, at least you shouldn't. It's a memory leak, or may point to no-longer-allocated memory.
What are you trying to do?
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
Sep 23rd, 2002, 07:48 PM
#6
Thread Starter
Frenzied Member
I have a class that uses char*'s throughout it, and I want to use strings in the rest. Can I convert from string to char*?
retired member. Thanks for everything 
-
Sep 23rd, 2002, 07:51 PM
#7
Frenzied Member
std::string::c_str() returns a const char*.
Z.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|