This question already has answers here:
can't modify char* - Memory access violation
(4 answers)
Closed 2 years ago.
int main()
{
char *p = "I like C++";
strcpy(p, "John Smith");
std::cout << p << std::endl;
EXIT_SUCCESS;
}
As the title stated, why does this results in segmentation fault
Speaking in the terms used by strcpy() documentation, you are trying to copy "John Smith" (the source argument) into p (the destination argument).
Although p is a pointer of type char *, it resides in the read-only data section (.rodata probably).
Trying to copy a new string into it, means trying to write over read-only memory.
Changing the declaration to char p[] = "I like C++"; fixes the issue as p now resides on the stach which is both readable and writeable memory.
By the way, the last line is missing a return and should be return EXIT_SUCCESS.
Related
This question already has answers here:
C++ return array from function [duplicate]
(7 answers)
Closed 2 years ago.
I'm creating some code to "parse" an IP address. Basically, I am working with some legacy code that only accepts IP addresses in the form "AAA.BBB.CCC.DDD" and would like to write in something like "10.2.4.3" and have the code work without needing to type in 010.002.004.003. The IP address is held in a char pointer and the function I wrote to add the zeros to the code returns another char pointer. Would the following main function be okay to use (i.e. no memory leaks or other issues)?
char* parser(char* ip) {
char out[16]; //16 is the length of the final IP address with the dots and \0 char at the end
//find output char array
return out;
}
int main() {
char *a="10.2.4.3";
a=parser(a);
return 0;
}
While my understanding of memory leak issues in C++ are that they are due to allocating with new and then not deleting at the end or allocating with new and then reassigning them, I'm honestly not sure in this case. Since a is statically allocated, does assigning it to the char pointer created in the parser function cause any type of memory leak or other issue?
No, you don't need a delete if you don't do any new. But your program suffers from a different problem:
char* parser(char* ip) {
char out[16]; //16 is the length of the final IP address with the dots and \0 char at the end
//find output char array
return out
}
This returns a dangling pointer. It won't be safe to access the returned value as it gets reused as soon as the function returns.
One way around that is minimally different from what you have is:
void parser(const char* ip, char* out) {
// todo: write to out here;
}
int main()
{
const char *a="10.2.4.3";
char out[16];
parser(a, out);
return 0;
}
But this would still look a lot like old C written in a C++ compiler. There's better constructs available.
This question already has answers here:
Why is address of char data not displayed?
(8 answers)
Closed 5 years ago.
Here in this code, cout<<q<<endl; is returning string "mani"?. q contain the address of first character 'm' so it should print address not string.please explain.
int main(){
char *q;
char b[5]={'m','a','n','i'};
q=&b[0];
cout<<b<<endl;
cout<<q<<endl;
std::cout has a special overload for const char*, which outputs the memory as an array of chars starting at the pointer passed up to the next NUL terminator (it's your job to make sure that the appropriate memory is available for that).
If you want to switch off this behaviour and output the pointer address then use a cast:
std::cout << (const void*)b << endl;
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
void changeString(const char* &s){
std::string str(s);
str.replace(0, 5, "Howdy");
s = str.c_str();
}
int main() {
const char *s = "Hello, world!";
changeString(s);
std::cout << s << "\n";
return 0;
}
When I run this code, it prints "Howdy, world!" I would think that str gets destroyed when changeString exits. Am I missing something with the way std::string gets allocated?
Yes, str is destroyed; but the memory of the string isn't cleared; your "s" pointer point to a free but non cleared memory. Very dangerous.
It's undefined behaviour when std::cout << s tries to access the pointer, because the destructor of the local std::string in changeString has freed the memory which the pointer still points to.
Your compiler is not required to diagnose the error but can instead generate a binary which can then do whatever it wants to.
The fact that you got the desired output was just bad luck because it made you think that your code was correct. For instance, I've just compiled your code on my machine and got empty output instead. It could also have crashed, or it may have done other, unrelated things.
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 7 years ago.
The code is:
char* c;
if(c!=NULL)
{
cout << "c has an address the address is "<<c;
}
else
{
cout << "c is null";
}
The output is:
c has an address the address is [Finished in 0.3s]
If c is not NULL, why c doesn't be printed out as an adress something like "0x401dee"
The problem with pointers is, that they often have a value after creating it, but its not a NULL pointer (!). But because its a pointer it points to a random address in your memory. That can cause pretty big problems, that's why you should ALWAYS initialize a pointer with
TYPE * NAME = NULL
So it hasn't a value and so it can't point to something, that could cause problems and now you can test with
NAME == NULL
(Of course you can also initialize it with a real value like the address of one of your variables)
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
char* func()
{
const int size = 24;
char bin[size];
char *temp;
for(int i=0; i<23; i++)
bin[i] = '1';
bin[23] = '\0';
temp = bin;
return temp;
}
int main()
{
char *s;
s = func();
cout << s << endl; //prints out weird values
return 0;
}
When compiled and ran, it print random values. In the function func, I initialized a char array and tried to return it. Upon returning it and printing it in main, it prints out weird values. What is wrong? Any help would be appreciated.
char bin[size];
allocate memory on the stack, you cannot refer to that location after the function returns: "char *s" is assigned a value that refer to an invalid memory location.
You must not use pointers to freed space, like the stack of a function which has finished executing.
This Undefined Behavior means anything goes, even the proverbial demons flying out of your nose.
Your choices:
Use a caller-allocated buffer.
Use a static buffer (beware reentrancy problems and multithreading woes).
Use dynamic allocation (new, new[], malloc() and friends).
return a struct (standard container or otherwise) containing the data. Might use dynamic allocation. (Last point courtesy of Matt McNabb).