我正在创建一些代码来“解析”IP 地址。基本上,我正在使用一些旧代码,这些代码只接受“AAA.BBB.CCC.DDD”形式的IP地址,并且希望写入类似“10.2.4.3”的内容,并且让代码工作而无需输入010.002 .004.003。 IP 地址保存在一个 char 指针中,我编写的用于将零添加到代码中的函数返回另一个 char 指针。下面的 main 函数可以使用吗(即没有内存泄漏或其他问题)?
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;
}
虽然我对 C++ 中内存泄漏问题的理解是,它们是由于使用 new 分配然后最后没有删除或使用 new 分配然后重新分配它们造成的,但老实说在这种情况下我不确定。由于 a 是静态分配的,将其分配给解析器函数中创建的 char 指针是否会导致任何类型的内存泄漏或其他问题?
最佳答案
不,如果您不执行任何新建
,则不需要删除
。但是您的程序遇到了不同的问题:
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
}
这将返回一个悬空指针。访问返回值并不安全,因为函数返回后它就会被重用。
一种与您所拥有的方法略有不同的方法是:
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;
}
但这看起来仍然很像用 C++ 编译器编写的旧 C 语言。有更好的结构可用。
关于c++ - 这种情况是否需要删除或创建新变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63348732/