Should I use delete when using this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    for (auto const &element: setB) {


        if (c++ < setA.size()) {
            if (TESTING) {
                cout << element;
            }

            // HOT FIX!!! FIND THE NEW LINE!!!
            // try catch for casting

            char const *test = element.data();
            bool passNewLineTest = true;

            try {

                if (test == (const char *) '\n')
                    passNewLineTest = false;

                delete test;

            } catch (const std::exception &e) {

                cerr << "Something went terribly wrong! " << endl;

            }

            itop.push_back(element);
            
        }
Last edited on
delete anything you get from new.

No new, so no delete.
That is what I thought. Usually my compiler complains if I use delete in the wrong place, so I wanted to double check! Thanks!
Never mind. I do not know what I was thinking!! I overlooked my compiler yelling at me! Taking a short break!
if (test == (const char *) '\n')

I don't think that's something you really want to do. Interpreting a character as a pointer value rarely ends well.
Your right. But it is of a string type so it should be good.
No, it's not good. It's a mess. This (const char *) '\n' creates a pointer that is pointing at the memory address 0x0000000a. It does NOT create a pointer that is pointing at memory containing the character '\n'. This reveals that you don't have a solid understanding of what a pointer is, which is definitely something to fix.

Ignoring the mess of this const char* cast, you're comparing pointers. You're not comparing characters. You're comparing two memory addresses.

If you had one char* that pointed to the string "beans" somewhere in memory, and another char* that pointed to the string "beans" somewhere else in memory, what do you think the result of this is?

first_char_pointer == second_char_pointer;

I'll tell you. The result is false.

Your code is fundamentally wrong because you think you're comparing strings, but actually you're checking to see if two pointers point at the exact same place in memory.
Last edited on
Topic archived. No new replies allowed.