简体   繁体   中英

C equivalent of C++ delete[] (char *)

What is the C equivalent of C++

delete[] (char *) foo->bar;

Edit: I'm converting some C++ code to ANSI C. And it had:

typedef struct keyvalue
{
  char *key;
  void *value;
  struct keyvalue *next;
} keyvalue_rec;

// ...

  for (
    ptr = this->_properties->next, last = this->_properties;
    ptr!=NULL;
    last = ptr, ptr = ptr->next)
  {
    delete[] last->key;
    delete[] (char *) last->value;
    delete last;
  }

Would this do it for C ?

free(last->key);
free(last->value);
free(last)

In C, you don't have new ; you just have malloc() ; to free memory obtained by a call to malloc() , free() is called.

That said, why would you cast a pointer to (char*) before passing it to delete ? That's almost certainly wrong: the pointer passed to delete must be of the same type as created with new (or, if it has class type, then of a base class with a virtual destructor).

Just plain 'ol free() . C makes no distinction between arrays and individual variables.

相当于deletedelete[]的C语言是free吗?

与非数组相同。

free(foo->bar)

The equivalent would be:

free(foo->bar);

since you were typecasting it to (char *) which means whatever the actual type of 'bar' was there would have been no destructor called as a result of the cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM