How memory allocated for string using new in c++ [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
I am just wondering how memory handling is done for a string object in c++.
I have below code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
string str = new char[30];
str = new char[60];
delete[] str;
return 0;
}
This piece of code will definitely throw an error, but can someone explain me in detail why this is an error ?
And will the above declaration assign a total of 90 bytes to str ?
Thanks in advance

std::string allocates it's memory internally. That's the whole point, it does the memory handling for you. So if you want to allocate a string of thirty characters you do it like this
string str(30, ' ');
This creates a string of 30 spaces. The memory allocated will automatically be deallocated when the string is no longer being used.
The string constructor your code used is actually meant to create C++ strings from C strings. E.g.
string str("hello");
This creates a string of length 5 and initialises it to 'hello'. Again any memory allocated will automatically be deallocated when the string is no longer used.
This is the point of the std::string class, to make things easy. Easier than you were prepared to believe apparently.

Related

Getting initializer-string for char array is too long. Is this a compiler error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
static_assert(0<decltype(AType::Id)::MaxIdLen);
using __type = char[decltype(AType::Id):: MaxIdLen + 10000];
[[maybe_unused]] __type aa = ""; //error initializer-string for char array is too long
I am getting this weird compiler error saying the initializer string is too long. But it is actually not. The first static_assert passed.
Has anyone seen such an issue before? I am using clang.
... compiler error saying the initializer string is too long. But it is actually not.
The compiler is not telling you that the string is too long to init aa. It's telling you that it's more data than it can handle, presumably because decltype(AType::Id)::MaxIdLen is a large value.
The compiler doesn't just store the string literal in the character array. It initialises the entire character array by using the string literal as a prefix, and padding the rest with zeros.

why can't I print the copied string individually? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
string s="1 23";
string a;
a[0]=s[2];a[1]=s[3];
cout<<a;
Here, I can't get output string a. But I can get all the individual elements by a[0].
Because a is empty, a[i] accesses it out of bounds for every possible i, causing undefined behavior.
Use a.push_back(s[i]) to add characters to a.
a is initialized as an empty string, so no memory is allocated for its characters, so when accessing it with [], you access unallocated memory, and that's undefined behavior.
One way to solve it is to create a as string with enough characters allocated. You can use the std::string fill constructor, that fills the string with a char of your choice:
std::string s = "1 23";
std::string a(s.size(), ' ');
This way you can put the characters in any index that exists in s.

Error in Strings assignment. (C++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I've looked everywhere and I've found one for php but not c++. I'm making a little console rpg for a project in my into to c++ class and I'd like to avoid functions and/or if possible--but if not I'll use them.
Sample code:
int main(){
string pName;
string pWpnName;
int pDamage=0;
int wdSwrdD=1;
if (pDamage==wdSwrdD)pWpnName="Wooden Sword";
cout<<"Please enter a name";
cin>>pName;
pDamage++:
cout<<"Name: "<<pName<<endl;
cout<<"Weapon: "<<pWpnName<<endl;
return 0}
But whenever I do this it outputs: Name: pName (like it's supposed to) and Weapon:. It just stays blank and I have a feeling it's something to do with how I'm using strings...
You do not understand basics of how imperative languages (and C++ is one of them) work. Program executed statement by statement, and your if condition checks pDamage==wdSwrdD only once - when execution flow goes through that statement. So the fact that you increase pDamage later will not magically change pWpnName (and you need to change comparison operator == to assignment operator = in that if condition in addition to that, but I assume this is a typo).
So you most probably need a loop where execution flow is repeatedly goes through your if statement (that's what loops are created for), but it is difficult to say anything more based on information you provided.
You can use the getline() function:
cout<<"Please enter a name"<<endl;
getline(cin, pName);
pDamage++;
The function can get a line from a stream, set std::cin as the steam argument, and assign a line input to a variable.
Your problem is that you've made a typo: == is equality comparison, while = is assignment. So, your section of code should be changed:
if (pDamage==wdSwrdD)
pWpnName=="Wooden Sword"; // here you're doing comparison
...to:
if (pDamage==wdSwrdD)
pWpnName="Wooden Sword"; // here you're doing assignment
Most compilers should generate a warning for this behavior because it's an easy typo to make, but can be difficult to catch.
In your program you have not initialized the strings and your are taking user input for pName and therefore it displays the name . In case pWpnName it's not initialized while declaring and the "if condition never becomes true" because you have initialized pDamage=0 and wdSwrD=1 and as we know if(0==1) is never true the string pWpnName never gets initialized to Wooden Sword so it displays blank.

Odd characters in output [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to write a simple hangman game in c++ by randomly selecting a word from a list, checking the string length, and writing that many *s into a new string to serve as placeholders in the yet un-guessed word. The max length is 9 letters. I have the game working almost flawlessly -- the problem is that whenever my word has 8 or 9 letters, the program prints the correct number of *s followed by one or two � characters. Research tells me these are unprintable characters, but I've tried for a while now and I'm not sure why they're here, why they only show up with a word length>7, or how to get rid of them. Below is relevant code. Any suggestions?
Generating *s:
char word[80];
int len=strlen(targetWord);
for(int i=0;i<len;i++){
word[i]='*';
}
You forgot to add the \0 terminator at the end of the string. After the for loop, add:
word[i] = '\0';
Or, best, use std::string instead of a C string.
Try using std::string instead.
std::string word;
int len=strlen(targetWord);
for(int i=0;i<len;i++){
word+='*';
}

Simple General Questions about C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Ive moved from autoit and am now learning C++ and some problems keep coming up.
The first one is storing character input. The problem is that I have no idea how many characters are in that line of the file (if you are reading a file) or how many letters a user is going to type (in a console application).
What is the best way to approach this problem?? I have heard about the string class, but I want to avoid it becuase I dont know how it works and that leads to vunerabilities etc.
Secondly...
In C you can load shellcode into memory, create a function pointer, and execute that code.
Is there any mechanism for this in C++???
Thirdly...
How does the interpreter iterate through char arrays for string output??? (char array[3];) Does the compiler keep track of the size of the array, or does it just keep reading from memory until it hits that \0 thing???
Lastly...
If Char * are just pointers to data in memory, then why does:
char * title = "Program Title";
this work??? where is the string literal stored in memory?? how is it referenced???
Thankyou very much. I greatly appreciate your help.
-Hyperzap
Investing your time in learning std::string is well worth the effort, as it takes care of a lot of hassle for you. If you don't want to take advantage of the features in C++, then why use C++ and not just C?
You can use the same code for this as you would in C.
Yes, iostream-output of C-style strings outputs until terminating zero. Once again, if you use std::string you do not have to care about such details.
Correct me if I'm wrong, but I think title would be a const char[] stored on the stack.
Example:
const char* hello = "Hello\0World";
cout << hello; // Prints only "Hello", i.e. up to terminating zero (\0)
The reason this works:
const char* hello = "Hello world";
cout << hello;
is because hello is really "Hello world\0"; - in other words, the compiler inserts a terminating zero.
Note that std::string doesn't do any magic. It too reads until the terminating zero:
string hello = "Hello\0World\n";
cout << hello; // Still only gives "Hello"
char* title = "String Literal" works because the compiler preallocates a memory location to store your string literal, thus you then get back a pointer to this memory location.
In c++, an array for which you know the size at compile time (as in your example: char array[3] is a type in itself, so the compiler does keep track of the size. However, if you do not know the size (ie. char array[]), it is just a pointer to char. However, you should be using std::vector in c++ (better safety and performance).
I'm not too sure about your other two questions (didn't quite understand them)