Some Name
Some Name

Reputation: 9521

Move implementation in C

I'm trying to implement a move function to be able to sort of move objects without copying their contents. Here is what I mean:

static void foo(const char* moved_content){
   //use moved_content
}

const char *string = //...
foo(string);
string = NULL;

So after I pass the string to foo no one else can access the string. I think this will make debugging easier in case of illegal access since e.g. on Linux I'm mostly likely to receive SEGV.

I tried the following:

static inline void* move(void **ptr){
    void *tmp = *ptr;
    *ptr = NULL;
    return tmp;
}

But I cannot use it like, say

const char *str = "string";
const char *moved = (char*) (move((void **)&str)); //this is non-conforming

I tried to write a macro using gcc extension but this seem no way to return a value from it:

#define MOVE(ptr) \
    do { \
        __typeof__(ptr) original_ptr = ptr; \
        __typeof__(*original_ptr) tmp = *original_ptr; \
        *ptr = NULL; \
    } while(0)

Is there a way to implement it conformingly? Probably _Generic is a way to go... Or explicitly setting the pointer to NULL is not that bad?

Upvotes: 2

Views: 415

Answers (1)

alk
alk

Reputation: 70951

As it seems you are willing to use extensions to the C language, your 2nd approach is almost there, just you need to go one step further by making it a "Statement Expression":

#define MOVE_AND_CLEAN(p) ( \
  { \
    __typeof__(p) p_tmp = p; \
    p = NULL; \
    p_tmp; \
  } \
)

Use it like this:

#include <stdio.h>

int main(void)
{
  const char * ps = "string";
  const char * pd = MOVE_AND_CLEAN(ps); 

  printf("ps = %p\npd = %p\n", (void*)ps, (void*)pd);
}

and get:

ps = 0x0
pd = 0x123456789

:-)

Upvotes: 2

Related Questions