tags:

views:

285

answers:

5

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)
+6  A: 

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).

James McNellis
I'm converting some C++ code to ANSI C. And it hadfor (ptr=this->_properties->next, last=this->_properties;ptr!=NULL;last=ptr, ptr=ptr->next) {delete[] last->key;delete[] (char *) last->value;delete last; }where typedef struct keyvalue { char *key; void *value; struct keyvalue *next;} keyvalue_rec;But plainfree(last->key);free(last->value);free(last);would do it for C?
inquam
@inquam: Do those pointers point to memory allocated using `malloc()`? If so, then use `free()` to free them.
James McNellis
A: 

The C equivalent to delete and delete[] is just free ?

Brian R. Bondy
I guess you mean `delete` and `delete[]`, otherwise we would be speaking different C and C++ dialects :).
Pieter
@Pieter: Yes that's what I meant :)
Brian R. Bondy
+2  A: 

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

Rakis
A: 

Same as for non-arrays.

free(foo->bar)
Tesserex
A: 

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.

Amardeep