-2
char * names( char * fname = new char[ 15 ], char * lname new char[ 25 ] )
{
     lname[ strlen( lname ) ] = ','; //adds a comma
     lname[ strlen( lname ) ] = ' '; //adds a space(lastname, firstname)
     strcat( lname, fname ); //concatenate fname to lname

     delete[ ] fname; //delete array
     return lname; //return lname
     delete[ ] lname; //delete array
}

I don't have much experience with dynamic arrays in C++, but I'm using one in a function I made. My understanding was that you could release the memory after your done using the array. But the program crashes if I delete it before using the return statement: Here is the function:

This makes it crash if I run it, but if I move the delete[ ] fname statement after the return statmenet, it works just fine. Why does it crash when I delete[ ] fname before the return statement? I concatenated fname to lname and returned lname. It shouldn't matter if I delete fname array before returning should it? Or can you not release memory like this?

Jess
  • 31
  • 1
  • 4

1 Answers1

1

It's not a very good c++ code. First of all it's not realy elegant doint what you do

char * names( char * fname = new char[ 15 ], char * lname new char[ 25 ] )

A function should not create something with his parameters, it should be a copy, a pointer or a referce to an object.

Second thing, it's normal that it don't crash if you put your delete after return, because it will never delete. The return will end the function and the other part of code will not execute.

Third you should use strings in C++. Strings manage memory by themself and you don't need to do horrible things like that.

A better way of your function can be.

std::string names(std::string fname, std::string lname)
{
    std::string fullname = lname + " ," + fname;
    return fullname;
}

And you can use it like that

names("MyName", "MyLastName");

//Result
"MyName, MyLastName"

The C Way (you should consider that your buffer are enough so give enough buffer size)

void name(char* infname, char* inlname, char* outfullname)
{
    char* a = ", "
    strcat(outfullname, inlname);
    strcat(outfullname, a);
    strcat(outfullname, infname);
}

So you can use it like

char fname[200];
char lname[200];
char fullname[500];

strcpy(fname, "MyName");
strcpy(lname, "Mylname");

name(fname, lname, fullname);

//fullname will be
"Mylname, MyName"
Captain Wise
  • 480
  • 3
  • 13
  • I knew using strings would be a better option, I was just trying to use dynamic arrays for practice. I don't understand how you would release the memory before returning the array. Or would dynamic memory not work correctly this way? – Jess Oct 09 '15 at 03:34
  • If you want to make it with a C way you should accept char pointer that the calling part of your code reated and you only need to do the manipulation. – Captain Wise Oct 09 '15 at 03:37
  • Look at my modifiation to my answer. – Captain Wise Oct 09 '15 at 03:46