0

If I have a structure:

typedef struct {
  unsigned char data[HEX_FLASH_BUFFER];
  bool isLoad;
  unsigned int length;
} s_hexFLASH;

typedef struct {
  s_hexFLASH flash;
} s_hexFile;

s_hexFile *hex = new s_hexFile;

How can I delete this whole structure? Because when a did something like this:

delete[] hex->flash.data;

After this I'am still able to read data:

cout << hex->flash.data[0] << endl;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lodhart
  • 635
  • 2
  • 9
  • 13

5 Answers5

4

unsigned char data[HEX_FLASH_BUFFER]; defines an array of fixed length with automatic storage duration, which means that it will be deallocated automatically when the structure object is deallocated.

In other words: you haven't allocated it by calling new[] so there is no reason to call delete[] on it.

LihO
  • 41,190
  • 11
  • 99
  • 167
4

You don't need to delete data, because it's not allocated dynamically in the first place. delete pairs with new. So call delete hex;

All that said, in modern C++ you basically don't use the delete keyword manually. You use the smart pointers shared_ptr and unique_ptr to manage dynamically allocated memory. But it is more usual just to use local (automatic) variables.

Also note: typedef struct { ... } name; should be just struct name {...};. The former is archaic.

Martin York
  • 257,169
  • 86
  • 333
  • 562
David
  • 27,652
  • 18
  • 89
  • 138
1

delete (and delete[]) simply deallocate dynamically allocated memory (and run the destructor for non-POD types, but that is not important now).

data here has automatic storage duration. Not only does delete[] not work here, it causes undefined behavior. A good compiler will warn you if you try do delete non-dynamically allocated memory.

Even when memory is no longer marked as 'in-use' you can still access it, but this causes undefined behavior.

Symaxion
  • 785
  • 7
  • 21
0
delete hex;

will delete the memory allocated to the hex structure

stan
  • 4,885
  • 5
  • 49
  • 72
  • @Lodhart: Well, more importantly to your question, the data array was not allocated dynamically, so there's no need to call delete on it. But hex was allocated dynamically. So that's where you call the delete. – stan Feb 17 '13 at 17:58
0

The member data does NOT have automatic storage duration. It has whatever storage duration the class it is the non-static member of has.