Dynamic memory allocation issue

Hello,
I have a function which returns Char * as output.I want to pass this output to major function.Now I should allocate proper memory to store this particular value - so I ahve done -

outputvariable type is char *;

1
2
3
4
5
char **passvalue;
char *vari = new char[sizeof(outputvariable) + 1]
strncpy(vari ,outputvariable,sizeof(outputvariable)-1);
*passvalue = vari;
delete vari;


Above code throws error message.Please let me know how can I get it corrected.
I have restriction of using char only not string.

Last edited on
Post the whole function.
You missed a ; on line 2..
If outputvariable is a char*, sizeof(outputvariable) = 4. What you need is strlen().
passvalue is not initialised, so you can't dereference it. You don't really need passvalue to be char**. In fact you don't need it at all. Just return vari.
When you delete arrays, use delete[]. And why would you delete vari?
tthe code pasted was just a portion of actual funstion so please ignore syntax errors.Now it works following way for me -

1
2
3
4
5
char **passvalue = NULL:
char *vari = new char[strlen(outputvariable)+1];		
strcpy(vari ,outputvariable);
*passvalue = vari;
//delete[] vari; 


But above way space allocated for "vari" remains as it is , as agood coding practise I should release memory allocated.but if I uncomment delete statement ,data assigned to "passvalue" gets deleted.Please let me know what correction I will need to make.
closed account (S6k9GNh0)
If your function returns vari, which is allocated on heap, then it must not delete vari before it returns or it will no longer be a valid pointer.

In the case of a C style function, you just have to be sure to make a distinction on whether you auto-delete the memory using a smart pointer, use some other method to delete the pointer (like a setup and shutdown function), or if the user of your function needs to delete the memory himself.

More often than not, if you aren't sure when the memory is going to need to be released, its usually best to just use a smart pointer.
Last edited on
Topic archived. No new replies allowed.