开发者

Should my functions copy `char*`-arguments?

Whenever i have a function that takes a c-string, and want to store its value inside a linked list, shou开发者_运维知识库ld i do it like this...

void add(char* str)
{
    node *n = malloc(sizeof(node));
    n->value = str;
}

or rather...

void add(char* str)
{
    node *n = malloc(sizeof(node));
    char* copy = malloc(strlen(str)+1);
    strcpy(copy, str);
    n->value = copy;
}

Thanks in advance.


it really depends on where are the arguments coming from, and what are your intentions with those arguments.

if you know that the strings passed as argument are always available through the entire lifetime of your linked list, and that they are not modified nor freed, or that there is no function which would have any side-effect affecting your linked-list, then you can simply copy the pointer and not bother to copy the entire string.

if any of the above is not true (by which i mean also if you don't know the answer to one of the above), then it will be safer to copy the entire string.

some specific examples:

  • you are developing a small application which reads a csv file, stores the values in a linked list for sorting, then writes the values back to an xml file: you have the control over the entire lifetime of your strings, you don't have to copy them.

  • you are writing a linked-list library possibly, distributed on the net, possibly used by hundreds of people active in all kind of field: you don't know what will be passed to your library, you don't know if the library user will free the string before manipulating the linked-list, then you copy the entire string.

also note that this kind of design decision is better documented somewhere: it is your responsibility as a developer to make clear that your function will store the pointer without copying the string, or that you will copy the string and will need another function call to release the memory. (this is called design by contract: you establish a contract between the code using your function and the function itself, you'd better respect it or you are going to have problems, in the form of data corruption or software crash). one possible way to make your intention clear is the use of an appropriately placed const keyword.


What is the ownership of str? Is it a malloced buffer with dynamic data? Does calling add in your program give ownership of the pointer to the linked list?

There is no correct answer, as it depends on how str is being used.


I would rather prefer the second option because:- - Even if it works, the code is not maintainable - First option leaves a large gap for dangling pointer, if the original string str is deleted. There is no way to determine how many copies of pointer str were actually made in the program. - Any memory tools will also complain, causing a bloated output and thus difficult to debug any actual memory problem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜