Hello!
I'm new in C++, and I have a basic question:

When I have a function:

void foo(str* s){
char* p;
p = new char[strlen(s)];
strcpy(p, s);
cout << s <<endl;

}

This function will take the length of s and in bytes and will allocate that much space in memory for p.
I want to do the same but ask the user to enter a string and then dynamicly allocate memory for the entered string, but it wouldnt compile for some reason, and i'd get a segmentation error. I know I can print s right away, but i want to allocate memory dynamicly in this exersize.
Here is the code I have so far:

int main(void){

	char* s;
	char* p;
	cout << "Please Enter a string: ";
	cin >> s;
	p = new char[strlen(s)];
	strcpy(p, s);
	cout << p <<endl;
	return 0;
}

Any help would be greatly appreciated.
Thank you!

Dani AI

Generated

Brief summary: the crash comes from reading into an uninitialized char* and from not reserving space for the terminating NUL. declared char* s; and then used input into s — that pointer points nowhere, so the input writes into random memory. and correctly called out the missing byte for the '\0' terminator and the uninitialized pointer. The modern, safer approach is to read into a managed string and only allocate a C-style buffer if you really must.

Safe pattern (keeps dynamic C-string but avoids leaks and UB):

#include <iostream>
#include <memory>
#include <string>
#include <cstring>

int main() {
    std::string line;
    std::getline(std::cin, line);                 // read whole line (spaces OK)
    std::unique_ptr<char[]> buf(new char[line.size() + 1]); // RAII-managed buffer
    std::memcpy(buf.get(), line.c_str(), line.size() + 1);  // copy including terminator
    std::cout << buf.get() << '\n';
}

Notes and troubleshooting tips:

  • Operator>> into a raw char* requires that the pointer already point to an allocated buffer; otherwise UB and likely a segfault. operator>> also stops at whitespace — use std::getline for full lines.
  • Always allocate room for the trailing NUL character when creating a C-string (hence size() + 1).
  • Prefer RAII (std::string, std::unique_ptr<char[]>, or std::vector<char>) to avoid manual delete[]. If using raw new[], pair it with delete[] and test with tools like Valgrind or ASan to catch overruns.
  • If portability and safety matter, stick with std::string throughout and avoid manual C-string copies unless an API demands them.

Recommended Answers

All 2 Replies

You forgot to allocate +1 byte for zero char terminating C-string:

p = new char[strlen(s)+1];

Now you have memory leak: you forgot to deallocate this memory:

delete [] p;

Well, it's evidently useless function...

The 2nd snippet:

char* s;
...
cin >> s;

Pointer variable s is not initialized, it points to nowhere, but you are trying to get a string in this undefined memory. The 2nd error: the same as in the 1st snippet.

It's C++ program, use C++ constructs (more robust and comfortable):

cout << "Please Enter a string: ";
string line;
getline(cin,line);
cout << line << endl;

Feel the difference ;)

You cannot get input to pointer s without first allocating it some memory. What you're doing is attempting to store to whatever memory address s points to, which could be pretty random!

If you've not allocated the memory, you don't control it. If you don't control it, you should not be trying to modify it.

And, when you allocate memory to hold a copy of a string, you need to use strlen( source ) +1 as the size of the new array - you've got to allow for the NULL terminator character.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.