runtime error in storing char into a pointer value [duplicate] - c++

This question already has answers here:
Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?
(19 answers)
Closed 8 years ago.
problem is in 15 and 16th line
i am unable to store char into
a pointer pointing to a string.
the problem is same as given in
my book.?do i need to change my
compiler dev c++?
plz help.
#include<iostream>
#include<conio.h>
using namespace std;
void reverse(char *str)
{
char *end=str;
char *beg=str;
char temp;
while(*end)
{
end++;
}
end--;
while(beg<end)
{
cout<<*beg<<" , "<<*end<<endl;
temp=*beg;
*beg=*end;
*end=temp;
beg++;
end--;
}
cout<<str;
}
int main()
{
char *str="saurabh";
reverse(str);
getch();
return 0;
}

char *str="saurabh";
You cannot manipulate "saurabh" because it is literal.
For this you should either copy it to char[],
Example,
char arr[20];
char *ptr = "Data";
strcpy(arr,ptr);

I know that you likely need to implement yourself reverse, but you can use std implementation for tests:
std::string s("abc");
std::reverse(s.begin(), s.end());

Related

Please explain char* return type in C++ [duplicate]

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 2 years ago.
I have written a simple C++ code, and its working fine. But I don't know how it is working. I am just replacing "l" with "r" using myfun().
The return type of myfun() is char*. If I am returning &(str[0]), that is, only the address of the first element of the array, then why is it printing the complete string "herloworld"? Please explain what return &(str[0]); is doing.
#include <iostream>
using namespace std;
char* myfun(char str[])
{
str[2] = 'r';
return &(str[0]);
}
int main()
{
char str[] = "helloworld";
char* word;
word = myfun(str);
cout << word;
}
The operator << is overloaded for the type char * such a way that it expects that the used pointer of the type char * points to the first character of a string.
So the operator outputs all characters of the passed string until the zero character '\0' is encountered.
Also pay attention to that arrays used in expressions with rare exceptions are converted to pointers to their first elements.
So this call
word = myfun(str);
is equivalent to
word = myfun( &str[0]);
On the other hand, a function parameter having an array type is implicitly adjusted to pointer to the element type.
So this function declaration
char* myfun(char str[]);
is equivalent to the following declaration
char* myfun(char *str);
The both declarations declare the same one function.
And within the function instead of this return statement
return &(str[0]);
you could write
return str;
Correspondingly in main you could write
cout << myfun(str);
without declaring and using the intermediate pointer word.

How to convert string to char? [duplicate]

This question already has answers here:
std::string to char*
(18 answers)
Closed 8 years ago.
I have a problem to output a string. Can you help me?
In the following, const char * i and const char ** o are given.
The statement, "*o = temp" produces an error, saying that "std::string" and "const char *" do not fit. What is the problem?
int mytask(const char * i, const char ** o)
{
std::string temp = std::string("mytask:") + i;
*o = temp; //How to modify?
return (0);
}
First of all you are trying to assign a local char pointer and use it in calling function, where it have already been destroyed. So instead you should do this. Assuming memory is allocated for o:
strcpy(*o,temp.c_str());
*o=temp means you are making the o point to a pointer that points to a std::string however o is a pointer that points to a char (or sequence of chars). This is not allowed. The other way around works: temp=*o because the std::string object defines what happens when you assign a char* to it (copy the null terminated string into the object). If you absolutely must copy from temp into the char* pointed to by o*. use strcpy() and std::string.c_str()
strcpy(*o,temp.c_str())
In C++, it's unusual to pass raw pointers around in this manner.
Returning 0 doesn't achieve much either.
I'd expect to see something like this:
std::string mytask(std::string const& i)
{
return "mytask:" + i;
}
int main()
{
std::string const number { '1' };
std::string const ret { mytask(number) };
}
The statement
strcpy(*o,temp.c_str());
didn't work. I resolved this problem by
*o = temp.c_srt();
instead. Thanks all anyway.

How to return a char* from a function in C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 9 years ago.
I have the following function in c++
char* Test::convertToSHA(const char* cc) {
const char* salt ="sh$^$##!&7hbfvatfacv####bagg=shjgvshvcbschj";
time_t currentTime;
time(&currentTime);
CCString startTimeString;
startTimeString.createWithFormat("%d", currentTime);
std::string s = cc;
s += startTimeString.getCString();
s += salt;
char *str = new char[strlen(s.c_str()) + 1];
int length=strlen(str);
unsigned char hash[length*2];
char hexstring[41];
sha1::calc(str,length,hash);
sha1::toHexString(hash, hexstring);
return hexstring;
}
And in the call i use
char* output=NULL;
output= Test::convertToSHA("hello");
This is causing my code to crash. Is there a problem with me returning a string ? How can i return from this function ?
You can never return a local pointer in C or C++. Instead, either pass the pointer as a parameter:
void Test::convertToSHA(const char* cc, const char* hexstring) {
//no change to body
//no return statement needed
}
//then when calling the function:
char hexstring[41];
convertToSHA(cc, hexstring);
//hexstring has been modified
Or just use std::string instead. Use the c_str() if you need to convert to a c-style string (you still can't return the pointer, though).
I'm assuming you're using this library. I find it odd that it claims to be written in C++ but doesn't take advantage of C++ idioms. The function modifies the pointer, and doesn't return anything, so you do need a local variable. Lucky for you, std::strings will happily accept a char [] argument.
std::string Test::convertToSHA(const char* cc) {
// ...
char hexstring[41];
sha1::calc(str,length,hash);
sha1::toHexString(hash, hexstring);
std::string ret(hexstring);
return ret;
}

Access violation error when reversing a string c++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
The following simple function should reverse a character array in place.
void reverse(char* str)
{
char* last = str;
// find end of the string
while(*last) {
++last;
}
// swap characters until the pointers meet in the middle
while(str < last)
{
--last;
char temp = *str;
*str = *last;
*last = temp;
++str;
}
}
int main()
{
char* a= "Hello";
reverse(a);
return 0;
}
The code compiles. But it throws a runtime error about access violation. According to the debugger the culprit is the line below:
char temp = *str;
Any ideas why it happens?
char* a= "Hello";
The pointer a points to a string literal. According to the standard, attempting to modify a string literal results in undefined behaviour. In the case of your implementation, the segmentation fault indicates that the compiler is choosing to place the string literal in non-modifiable memory.
Declare a to be a string that is modifiable. For example, like this:
char a[] = "Hello";

c++ segfault: char pointers [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you reverse a string in place in C or C++?
Why is this C code causing a segmentation fault?
Modifying value of char pointer in c produces segfault
Running a very simple code example
#include <stdlib.h>
#include <iostream>
char* last_char(char* s){
char* last = s;
while (*last) ++last;
return last;
}
char* in_place_reverse(char* s) {
char* left = s;
char* right = last_char(s);
char temp;
while( left < right ) {
temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
return s;
}
int main(){
char * s = "letters\n";
std::cout << in_place_reverse(s);
}
All the time I get
Segmentation fault
But from my point of view I'm not doing anything illegal within the code.
Please help me to determine what's wrong.
P.S. I compile with
g++ example.c
Two problems:
You are trying to modify a string literal. This may work, it may not, or it may crash. This is invoking undefined behavior. Use char s[] = "letters\n" to make a mutable copy.
last_char() in fact returns a pointer to the sentinel '\0' at the end of the string -- it points beyond the last character. Change return last to return last - 1. Otherwise you are going to move the sentinel around too, and that's almost certainly not what you want. (Note that this will return a pointer to garbage if the string is zero-length. You should fast-succeed in in_place_reverse() if *s == '\0' to avoid this complexity.)
You are modifying a string literal and string literals are non-modifiable.
Use char s[] = "letters\n"; instead