Memory allocation question in C++ -


int main() {    char** k;    k = new char*;    char* k1 = "abc";   char* k2 = "def";    *k = k1;   *(k + 1) = k2;   delete [] (k + 1);   } 

error: segmentation fault

could explain why segmentation fault when freeing (k + 1)? able free k no problems.

add: in answers has been said can't delete [] (k + 1) since haven't used new on it; how explain fact cout<<*(k + 1)<<endl; printed correctly?

k = new char*; 

this allocated storage single char*.

*(k + 1) = k2; 

this tries pretend there 2 char*s allocated. may not site of segfault, error.

delete [] (k + 1); 

here you're trying delete[] did not new[], error.

edit: deep down, memory allocated in large chunks, such pages. when allocate small bit of storage, it's memory around valid. it's still invalid access it, though.

more point, when new char*, turns call operator new(sizeof(char*)). let's os allocates new 4k page of physical ram @ address 0x12340000. memory manager needs small structure in there keep track of block, like:

struct mem_block_info {     void* next_block;     size_t block_size; }; 

so puts structure @ 0x12340000. after that, puts storage requested, (assuming 32-bit machine) returns pointer of 0x12340008, since sizeof(void*) == sizeof(size_t) == 4. needs put header after storage track unused part of 4k page, doesn't waste memory allocating 4k page when want char*. header goes @ address right past end of allocated block, 0x1234000c. once dust settles, new char* has put in memory:

address    data 0x12340000 0x00000000 0x12340004 0x00000001 0x12340008 uninitialized; 0x1234000c 0x00000000 0x12340010 0x00000ff4 

the null pointers indicate end of allocated , free block linked lists.

so when do:

*(k + 1) = k2; 

k + 1 == 0x1234000c next_block pointer free block, , overwrote invalid value (the address of string in read-only memory, likely). not cause segmentation fault, when memory manager tries traverse free block list, wind looking @ string , misinterpreting block header, going next_block there invalid address, , boom, segfault.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -