views:

101

answers:

2

debug src: http://www.cppblog.com/Files/mymsdn/cvector-bug-vs2008-201007101651.zip

Hey all, I have repair my code, thanks yours help! You can download the correct version of my code.

src: http://www.cppblog.com/Files/mymsdn/cvector-vs2008-20100710.rar

I am trying to write a C language version of vector. I use the void ** a the pRoot indicate the pointer vector. I want to keep the void ** p available, than I malloc a memory.

like this :cvector_ptr_ptr = &cvector_ptr;

I pass the cvector_ptr_ptr to each function to deal with it.

In my code, I encounter a unhandled exception. I think I have read overrun. But in the function "insert", I can use (*cvector_ptr_ptr)->element_size to get the size value. I pass the cvector_ptr_ptr to the function "insert_copy" I can't use the same code [(*cvector_ptr_ptr)->element_size] to get the value.

What's wrong with me?

A: 

I think your code has many problems, one problem that is really evident is

offset = ((*cvector_ptr_ptr)->count + 1) * element_size;
                                    ^^^
                            this is the problem

The first element you add should be written to offset zero, not element_size.

6502
The code haven't setp into this line.......get the unhandled exception before....
Eric Kung
+1  A: 

The problem is in your "create_vector_n" function, there:

cvector_ptr_ptr = &cvector_ptr;
return cvector_ptr_ptr;

You are returning a pointer to a stack variable (cvector_ptr), which is terribly wrong.

PiN
I think it copy the value of cvector_ptr_ptr to the result (out of scope), but the *cvector_ptr_ptr is also available, because it's created from malloc. And the function "insert" is available
Eric Kung
No, it really returns an address somewhere into a stack. However - it may actually work for a while! At least until that stack value is overwritten by another function call for example.
PiN
I think you are right.
Eric Kung
it may actually work for a while! ———————————— is it the right reason of why function insert is ok and the function insert_copy encounter a crash? What's the best practice of this pattern? I move the variable into the global variable.
Eric Kung