C++ pointers and free() [Solved] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 13

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 ?

9th Jul 2019, 7:41 AM
Uni
Uni - avatar
3 Answers
+ 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 :)
9th Jul 2019, 8:28 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 8
Ok I see now thank you Aaron Eberhardt .
9th Jul 2019, 8:30 AM
Uni
Uni - avatar
+ 2
I'm sorry, I couldn't stop writing so the answer got a bit longer than I expected 😂
9th Jul 2019, 8:29 AM
Aaron Eberhardt
Aaron Eberhardt - avatar