passing string literal to function is not allowing to modify [duplicate] - c++

This question already has answers here:
Segmentation fault reversing a string literal [duplicate]
(4 answers)
Closed 8 years ago.
Program 1:
void function(char arr[])
{
arr[0] = 'X';
printf("%s",arr);
}
int main()
{
function("MyString");
}
Output: Segmentation fault
Program 2:
int main()
{
char arr[] = "MyString";
arr[0] = 'X';
printf("%s",arr);
}
Output: XyString
What is the difference between program 1 and program 2? In prog1 also string value (not by reference) is passed to array so it should copy to array and allow to modify it? But it is throwing segmentation fault. In prog2 successfully allowing to change the arr[]. Why in prog1 it is not working?

Prog 1: You are passing a string literal, which is sent to the function as const char*. You can not change a const object.
Prog 2:You are using a non-const character array, which can be modified.
From your comment:
In prog1 also string value (not by reference) is passed to array so it should copy to array and allow to modify it?
Wrong. In program 1, the string literal is placed somewhere in memory (possibly in read only memory since it is constant), and then a const char* which points to that memory location is sent. The character array is not sent as parameter, only the address of first character.

Related

C++ returned array loses it's values depending on if any new array is declared or not. Its losing it if yes [duplicate]

This question already has answers here:
Returning an array using C
(8 answers)
Closed 6 months ago.
I wrote a simple c++ program where i am getting a simple float Array from a function. Then I call a function where the generated Array is a parameter of. I print the first value of the Array through the function. It works! BUT when i am declaring another array in the function before i print the value from the first array, the printed value is not the expected one. MAGIC!
CODE THAT DOESN'T WORK:
#include <iostream>;
float* getArray() {
float Array[] = { 4 };
return Array;
}
void compute(float* Array) {
bool newArray[1];
float content = Array[0]; //breakpoint: content will be -107374176.
std::cout << content;
}
int main() {
float* Array = getArray();
compute(Array);
}
OUTPUT: -1.07374e+08
When removing the line "bool newArray[1];" (line 10) the code starts to work.
OUTPUT: 4
Test it your self! Can someone explain me why this happens?
Your main function has a bug. It passes a pointer to Array to compute, which dereferences it. But Array is out of scope at this point since its scope ends when getArray ends. So you are trying to access an object that no longer exists. That is undefined behavior and produces completely unpredictable results.
Arguably, getArray also has a bug since it always returns a pointer to an object that no longer exists. So there is no way to use it. Whether or not that's a bug depends on what the caller is supposed to be able to do with the returned value which cannot be determined due to the lack of comments.

Does this situation require a delete or making a new variable? [duplicate]

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.

Why this code is printing string rather than printing address? [duplicate]

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;

Storing a character in a char pointer which was initialized with string [duplicate]

This question already has answers here:
Why can't I write to a string literal while I *can* write to a string object?
(4 answers)
Closed 7 years ago.
I tried running the following program:
#include <iostream>
using namespace std;
int main(){
char *x = "Linux";
*x = 'T';
cout<<"value: "<<*x<<endl;
}
According to me, it should have stored 'T' in the location pointed to by x. But instead it gave segmentation fault. But when I did:
char *x;
*x = 'T';
The output was as expected. Can somebody explain this behavior?
Using a non-const char pointer to a string literal is deprecated and should not be used in new code. Modifying a string literal is undefined behavior. Your second example dereferences an uninitialized pointer which is also undefined behavior. That means it can sometimes appear to work.
String literals are const char*s, not char*s.
Both of your examples are undefined behavior; the second one appearing to work only occurs by accident.

C++ Returning an Array and Assigning It to a Variable [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 8 years ago.
So I have a homework problem that asks that I write a function that takes an array of chars, a char, and an int pointer. The function should loop through the array of chars, ignore any instance of the second parameter char, and create a new array which is composed of the characters in the original array other than instances of the second parameter char. Then the original length parameter needs to be changed to the new length, and the new array should be returned. I'm very new to C++ so pointers are a new concept which I haven't fully grasped yet.
char *Problem5(char chars[], char letter, int *length){
int newLength=0;
int counter=0;
for(int i=0;i<*length;i++){
if(chars[i]!=letter){
newLength++;
}
}
char newChars[newLength];
for(int x=0;x<*length;x++){
if(chars[x]!=letter){
newChars[counter]=chars[x];
counter++;
}
}
*length=newLength;
return newChars;
}
There is my function, I know the algorithm works fine but it won't compile.
char chars2[10] = {'g','g','c','g','a','g','g','g','t','g'};
printArray(chars2,10);
char *arrayPointer;
arrayPointer = Problem5(chars2,'g',length1);
printArray(arrayPointer,3);
And this is the section of my main function where it is called. I need to print out the resultant array, and so I try to assign it to a pointer, but this line:
arrayPointer = Problem5(chars2,'g',length1);
Throws an error: Invalid conversion from 'char' to 'char*' A little insight would be very much appreciated because I have no clue what I'm doing wrong.
Your algorithm looks ok and your code looks pretty much all right. I am a little skeptical of this line :
char newChars[newLength];
because you can't allocate an array at compile time with a variable size. Is it possible that the code you posted isn't exactly the code you tried to compile?
Change the line above to
char *newChars = new char[newLength];
and the array will be allocated dynamically at run time. I cannot understand why you would get an "Invalid conversion from 'char' to 'char*'" error compiling
arrayPointer = Problem5(chars2,'g',length1);
given the definitions that you've provided. The only things that have type "char*" are the first parameter to and return value from Problem5, and those look to be the correct types from what you've posted.