I have this simple program in which I want to concatenate two char pointers using memcpy, but I get access violation reading location on the memcpy line.
char *first = new char[10], *second=new char[10];
first="Hello ";
printf("\second: ");
scanf("%s",&second);
memcpy(first,second,strlen(second)+1);
printf ("Result: %s\n", first);
Because copying into a constant gets me the violation, I tried this:
char *first = new char[20], *second="world!";
printf("first: ");
scanf("%s",&first);
memcpy(first,second,strlen(second)+1);
printf ("Result: %s\n", first);
which gets me access violation writing location. How should I concatenate correctly the two pointers?
Your memcpy is equivalent to memcpy ("Hello ", second, strlen(second)+1);. Copying into a constant is (on some platforms, apparently including yours) an access violation.
char *first = new char[10], *second=new char[10];
first="Hello ";
First you make first point to some memory you allocated. Then you throw that pointer away and make it point to a static string. That's not what you mean. Maybe you meant:
strcpy (first, "Hello ");
This copies the constant's data into the space first points to.
char * concat(const char * first, const char * second)
{
int lf = strlen(first);
int ls = strlen(second);
int len = lf + ls;
char * rb = new char[len+1];//You need this +1 here
memcpy(rb, first, lf);
memcpy(rb+lf, second, ls);
rb[len] = 0;
return rb;
}
int main ()
{
char *first = new char[10], *second=new char[10];
strcpy(first, "first");//This is an unsafe way. You can take the value from anywhere possible
strcpy(second, "second");//This is an unsafe way. You can take the value from anywhere possible
char * third = concat(first, second);
cout << third << endl;//Don't use cout << concat(first, second) << endl; since it leads to a emory leak
delete [] third;
return 0;
}
You can't concatenate two string without using extra memory, since every time you need a memory block of size of the sum +1 (or more) of the two given strings.
Change
scanf("%s", &first);
to
scanf("%s", first);
You access the wrong memory when scaning.
Related
I'm doing an exercise in which I have to copy a c-style string into memory allocated on free store. I am required to do it without using subscripting and relying solely on pointer arithmetic. I wrote the following function-
char* str_dup(const char* s)
{
// count no. of elements
int i = 0;
const char* q = s;
while (*q) { ++i; ++q; }
//create an array +1 for terminating 0
char* scpy = new char[i + 1];
//copy elements to new array
while (*s)
{
*scpy = *s;
++s;
++scpy;
}
*scpy = 0;
return scpy;
}
The function is returning random characters. But if I change it into this-
char* str_dup(const char* s)
{
// count no. of elements
int i = 0;
const char* q = s;
while (*q) { ++i; ++q; }
//create an array +1 for terminating 0
char* scpyx = new char[i + 1];
char* scpy = scpyx;
//copy elements to new array
while (*s)
{
*scpy = *s;
++s;
++scpy;
}
*scpy = 0;
return scpyx;
}
it works. Can someone explain me why first code is not working and second is working?
The first code is not working since you return the final value of scpy, which at that point points at the terminating NUL character, and not the start of the string.
One solution is to do as you did, and save a copy of the original pointer to have something to return.
You should really use strlen() and memcpy(), they make this easier but perhaps they're off-limits to you.
I have been given a task, where I need to create the string_copy function Note that the function body and prototypes have been given by the source and that needs to be maintained. The portions written by me are after the comment write your code here.
#include <iostream>
using namespace std;
int string_length(const char* string_c);
char* string_copy(const char* string_c);
int main()
{
const char* string_c = "This is a string and is a long one so that we can create memory leaks when it is copied and not deleted";
// write your code here
int length = string_length(string_c);
cout << "Copied String: " << string_copy(string_c) << endl;
return 0;
}
int string_length(const char* string) {
int length = 0;
for (const char* ptr = string; *ptr != '\0'; ++ptr) {
++length;
}
return length;
}
char* string_copy(const char* string) {
// we need to add 1 because of ’\0’
char* result = new char[string_length(string) + 1];
// write your code here (remember zero-termination !)
int i;
for (i = 0; string[i] != '\0'; ++i)
{
result[i] = string[i];
}
result[i] = '\0';
return result;
}
Now task tells me
that it is very important that any memory allocated with e=new TYPE is
released later with delete e (and a=new TYPE[size] with delete [] a)
else this will lead to an error.
It is not exactly clear if error means compile/runtime error or error as in my task did not meet the requirement error.
My question is, in this code how do I delete the intermediate dynamically created result array? If I delete result, won't it fail the purpose of the task? Then how am I to respect the quotation above or maybe simulate memory leak as given in the long string constant?
Thanks.
EDIT: Why the negative votes? Please at least explain the reason! I am not asking any solution or something, but mere suggestion if I am missing some point or not!
The caller of string_copy would be responsible for releasing the memory when it's done with it by calling delete[] on it.
This is, by the way, a terrible way to write C++ code. You should be using std::string or std::vector<char> or something like that.
Here's why:
int length = string_length(string_c);
char* copy = string_copy(string_c);
cout << "Copied String: " << copy << endl;
delete[] copy;
return 0;
Yuck.
In fact the ideal solution is to use std::string and not char *. There is no real need of using char * instead of std::string in your example.
With std::string:
You don't need to new anything
You don't need to delete anything
You can do everything with std::string, that you do with char *.
I wrote a function which receives as a parameter a char pointer,then builds a new dynamic allocated char array that contains that parameter char.Then,it returns the new char array.
This is the function:
char* read_string(char *pstr)
{
char *str;
str = new char[strlen(pstr)];//allocate memory for the new char
str[strlen(pstr)] = '\0';
for(unsigned i=0;i<strlen(pstr);i++)//build the new char
str[i]=pstr[i];
return str;//then return it
}
In main I have:
int main()
{
char *Pchar = read_string("Test");
cout<<Pchar;// Outputs "Test"
delete [] Pchar;//"Program received signal SIGTRAP, Trace/breakpoint trap." error
}
I declare a char pointer in main and then make it point to the char array that is returned from the read_string function.It outputs what I want but if I want to free the memory it gives me runtime error.How can I free up the memory if I don't need to use Pchar anymore?
EDIT:Thank you all for your very informative answers.I have successfully resolved the problem.
You need to allocate more memory to have space for EOS character:
str = new char[strlen(pstr)+1];
Your specific problem is an off-by-one error:
str = new char[strlen(pstr) + 1];
// ^^^^ need one more for the '\0'
str[strlen(pstr)] = '\0';
Generally, since this is C++ and not C, it would be better to return a smart pointer so the caller knows what the ownership semantics of the pointer are:
std::unique_ptr<char[]> read_string(char *pstr)
{
std::unique_ptr<char[]> str(new char[strlen(pstr) + 1]);
// rest as before
return str;
}
It seems that the error occurs due to incorrect length of the allocated string.
You have to use the following record to allocate the string
str = new char[strlen(pstr) + 1];//allocate memory for the new char
str[strlen(pstr)] = '\0';
The function can look the following way
char* read_string( const char *pstr )
{
char *str;
size_t n = strlen( pstr );
str = new char[n + 1];//allocate memory for the new char
strcpy( str, pstr );
return str;
}
Right off the bat, I'm required to use dynamically allocated character arrays for my assignment, so do NOT suggest I just use strings. I need to create a method that accepts a character array as an argument, and inserts that character into a char* using strcpy. How do I do this without first initializing the char*?
Here is my code so far:
char* char_array;
char test_array[] = {'t','e','s','t','\0'};
strcpy(char_array, test_array);
Your char_array is just an unitialized pointer. You need to dynamically allocate memory for it and then carry out strcpy.
char* char_array = new char[6];
char test_array[] = {'t','e','s','t','\0'};
strcpy(char_array, test_array);
Or as suggested by Joachim you can use strdup() to duplicate a string - it will allocate the memory and copy the string into it.
In both cases, don't forget to free() (or delete[]) the resulting memory once you're done with it.
You can't do that unless you actually allocate a chunk of memory for char_array through malloc or new.
int length = 6;
char* char_array = (char*) malloc(sizeof(char) * length);
or
char* char_array = new char[6];
char * char_array = NULL;
void yourFunc(char your_array[]) {
if (NULL != char_array) {
free(char_array);
char_array = NULL;
}
char_array = (char *)malloc(sizeof(char) * strlen(your_array));
strcpy(char_array, your_array);
}
you stated you need a method/function that accepts a char[]/char *
you have stated your constraints ...
this does seem to be low level for instructional purpose
I assuming null terminated character array and valid source character array
//function accepts character array
char * charseqduplicate(char * s)
{
//low level c
const int len = strlen(s) + 1;;
char * copy = new char[len];
strcpy(copy, s);
//remember to delete or use something like unique_ptr
return copy;
}
void letsdothis()
{
//low level c
char test[] = {'y','e','s',char(0)};
char * dup = charseqduplicate(test);
cout << dup;
delete [] dup;
}
A little context: I'm trying to make a very simple hashing function/hash table as described here. I'm basically on the first step, blindly adding a key to an array based on the letter it starts with (no checking if space is occupied yet). The code I'm using to do this so far:
int main(int argc, char **argv) {
char *arrayKeys[300];
std::string aName("Charles");
char *aNameCpy = new char[aName.size() + 1];
std::copy(aName.begin(), aName.end(), aNameCpy);
aNameCpy[aName.size()] = '\0';
int kPos = storeKey(arrayKeys, aNameCpy);
std::cout << "The new position in arrayKeys for 'Charles' is: " <<
kPos << "\ncontaining the text: " << arrayKeys[kPos] << std::endl;
delete[] aNameCpy;
return 0;
}
int storeKey(char **keys, char *key) {
int charLett = -1;
charLett = (int)key[0];
if(charLett != -1)
charLett = charLett - 65;
keys[charLett * 10] = key;
return charLett*10;
}
My question is, how can I add a string to the array (arrayKeys) where it is fully apart of the array, and not reliant upon the original string? If I delete the copy of the string (aNamCpy) before I print the array key out, the array key turns into garbled symbols. I'm copying the string before sending it to the function because I need a non-const string to add to the arrayKeys array (so it can be modified), and any method of string I looked at seemed to return const.
(Another version of this I attempted can be found here, but I would rather not initialize the arrayKeys like that - with a definite second dimension (string) length)
C++ is still very new to me so I can't figure out how to juggle the non-const part with copying the string into arrayKeys. Any help would be very much appreciated.
Here's how I'd change the code to use more modern C++ constructs. I think you'll find this way easier to use.
int storeKey(vector<string> &keys, const string &key) {
int charLett = -1;
if (!key.empty()) { // you weren't doing this before!
charLett = key[0];
charLett = toupper(charLett) - 'A';
keys[charLett * 10] = key;
}
return charLett*10;
}
int main() {
vector<string> arrayKeys(300);
std::string aName("Charles");
// No need to bother with the awkward copying.
// std::vector and std::string will take care of it for us.
int kPos = storeKey(arrayKeys, aName);
if (kPos >= 0) {
cout << "The new position in arrayKeys for 'Charles' is: " <<
kPos << "\ncontaining the text: " << arrayKeys[kPos] << endl;
}
// Don't have to remember to delete anything because nothing was new'ed.
return 0;
}
(#Kristo has the right idea. I'm just going to add a comment to the question as asked.)
Basically, don't delete aNameCpy. You require the copy to remind valid and therefore it shouldn't be deleted. You should only delete the strings if and when you ever delete the entire hash.
C++ is still very new to me so I can't figure out how to juggle the
non-const part
You could declare both keys and key to be const char **keys, const char *key. keys is pointer-to-pointer-to-char. More precisely, it's a pointer to nonconst pointer to const char. In other words, you can modify keys, you just cannot modify the actual characters it points (indirectly) at.
So, simply put const in your declaration of storeKey int storeKey(const char **keys, const char *key) and update arrayKeys accordingly const char *arrayKeys[300];
One final style issue: You should copy the string inside storeKey, not in main. This is better design, as it makes clear to the reader that storeKey "owns" the copy.
int storeKey(char **keys, const char *key) {
char * the_copy = new char[strlen(key)+1];
strcpy(the_copy, key);
... and so on
But, in short, use C++ string instead of all this, if you can!