2

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?

Cayden
  • 29
  • 5
  • you forgot semicolon here ```return out;``` – Denys_newbie Aug 10 '20 at 22:22
  • When `parser` returns, the `out` pointer refers to destructed array. Probably not so useful. – Eljay Aug 10 '20 at 22:28
  • The code does not hold the IP address “in a char pointer”. It holds it in an **array of `const char`” and uses a pointer to that array. But the type of the pointer should be `const char*`. As written the code is ill-formed. – Pete Becker Aug 10 '20 at 22:36
  • “parser” is not the right name for this function. Functions are actions; their names should be verbs. Nouns are for objects. – Pete Becker Aug 10 '20 at 22:41

1 Answers1

4

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.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • Ah yes, you're right, I didn't even think about the issue with out being a dangling pointer once the function ended as it was constructed in the parser function. You're right about the code looking a lot more like old C as most of the old code is was written a while ago in C, but is being used in a C++ program. – Cayden Aug 10 '20 at 22:40