Does this situation require a delete or making a new variable?

Viewed 68

I'm creating some code to "parse" an IP address. Basically, I am working with some legacy code that only accepts IP addresses in the form "AAA.BBB.CCC.DDD" and would like to write in something like "10.2.4.3" and have the code work without needing to type in 010.002.004.003. The IP address is held in a char pointer and the function I wrote to add the zeros to the code returns another char pointer. Would the following main function be okay to use (i.e. no memory leaks or other issues)?

char* parser(char* ip) {
    char out[16];    //16 is the length of the final IP address with the dots and \0 char at the end
    //find output char array
    return out;
}

int main() {
    char *a="10.2.4.3";
    a=parser(a);

    return 0;
}

While my understanding of memory leak issues in C++ are that they are due to allocating with new and then not deleting at the end or allocating with new and then reassigning them, I'm honestly not sure in this case. Since a is statically allocated, does assigning it to the char pointer created in the parser function cause any type of memory leak or other issue?

1 Answers

No, you don't need a delete if you don't do any new. But your program suffers from a different problem:

char* parser(char* ip) {
    char out[16];    //16 is the length of the final IP address with the dots and \0 char at the end
    //find output char array
    return out
}

This returns a dangling pointer. It won't be safe to access the returned value as it gets reused as soon as the function returns.

One way around that is minimally different from what you have is:

void parser(const char* ip, char* out) {

    // todo: write to out here;
}

int main() 
{
    const char *a="10.2.4.3";
    char out[16];
    parser(a, out);

    return 0;
}

But this would still look a lot like old C written in a C++ compiler. There's better constructs available.

Related