سؤال

Let's assume I want to use a library that contains these 2 headers:

// types.h
typedef const char* Value;
typedef const char* Key;

// map.h
/** The given name and value will be copied into the map */
void add(struct Map* m, Key key, Value value);

I'm assuming the comment means that the contents of the char*s key and value will be copied by the add function, and it won't store the pointers for use after it has returned. That means the calling function can do whatever it wants with those pointers, like e.g. freeing key and value, immediately after calling add.

The calling function can also expect that add will not modify key or value.

Now what would the experienced C programmer assume about these ownership issues if that comment wasn't there and neither sources of the implementation nor a usage example were available?

هل كانت مفيدة؟

المحلول

First & foremost is to try & get the documentation. One cannot be 100% sure unless the API documents the behavior. If all attempts fail then it is reasonable to assume that:

  1. Function does not modify either Key or Value since they are passed as const.
  2. Unless explicitly mentioned the caller retains the ownership of the variables being passed to the function and can do whatever they want with the passed Key and Value after the function call.

Also, One should confirm the assumptions with rigorous testing.

نصائح أخرى

Personally, I would expect it to copy the values. Because if it wouldn't it would be very dangerous to use with local variables.

Also, in case of a map, you would have to track all the elements and how they where allocated and free them yourself after freeing the map if the copy wouldn't happen.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top