#include <iostream>
#include <string.h>
using namespace std;
void newBuffer(char* outBuffer, size_t sz) {
outBuffer = new char[sz];
}
int main(void) {
const char* abcd = "ABCD";
char* foo;
foo = NULL;
size_t len = strlen(abcd);
cout<<"Checkpoint 1"<<endl;
newBuffer(foo, len);
cout<<"Checkpoint 2"<<endl;
cout<<"Checkpoint 2-A"<<endl;
memset(foo, '-', len);
cout<<"Checkpoint 3"<<endl;
strncpy(foo, abcd, len);
cout<<"Checkpoint 4"<<endl;
cout << foo << endl;
int hold;
cin>>hold;
return 0;
}
This program crashes between checkpoint 2-1 and 3. What it tries to do is to set the char array foo to the char ‘-‘, but it fails because of some access issues. I do not understand why this happens. Thank you very much in advance!
Your
newBufferfunction should accept the first parameter by reference so that changes made to it inside the function are visible to the caller:As it is now, you assign the result of
new char[sz]to the local variableoutBufferwhich is only a copy of the caller’sfoovariable, so when the function returns it’s as if nothing ever happened (except you leaked memory).Also you have a problem in that you are allocating the buffer to the size of the length of
ABCDwhich is 4. That means you can hold up to 3 characters in that buffer because one is reserved for the NUL-terminator at the end. You need to add+ 1to the length somewhere (I would do it in the call to the function, not inside it, becausenewBuffershouldn’t be specialised for C-strings).strncpyonly NUL-terminates the buffer if the source string is short enough, so in this case you are only lucky that there happens to be a0in memory after your buffer you allocated.Also don’t forget to
delete[] fooinmainafter you’re done with it (although it doesn’t really matter for a program this size).