+12

C++ pointers and free() [Solved]

So I have this bit of a C++ program:(assume that has_space and range are well defined and throw no error) std::string s; getline(std::cin,s); if(has_space(s)){ std::vector<int> v = range(s); int debut = v[0], *fin = new int; fin = &v[1]; delete fin; The thing is that fin points indeed at v[1] and I can see it's memory location and value (*fin). Now the problem is that the delete part doesn't work : I get "free() invalid pointer". Can please anybody tell me why ?

7/9/2019 7:41:44 AM

🦄Uni🦄

3 Answers

New Answer

+4

I don't think it makes sense what you're trying to do there. Why would you free the memory of a member of your vector? This could lead to serious bugs if this memory cell is overwritten you vector might hold a value it shouldn't have. So my point is, it doesn't make sense to free fin unless you freed the whole vector. And then you probably won't even need to free fin anymore. P. S. fin is dangerous itself because if the vector changes (e.g. by push or pop) it might reallocate itself and fin would be a dangling pointer. Also you might want to read something about Rust. This language will always take care of your memory and doesn't allow you to write this king of bugs :)

+8

Ok I see now thank you Aaron Eberhardt .

+2

I'm sorry, I couldn't stop writing so the answer got a bit longer than I expected 😂