我想用 C++ 创建程序,并在我的服务器 FTP 上登录,如果服务器文件夹中有新文件,就会发生这种情况。
我的 friend 已经创建了这个程序,它正在运行(工作)并将它传递给我。
在程序内部,我们使用 CURL 的库和工具在 FTP 上登录。
在我的电脑上,这个程序无法使用 DEV C++ 运行。 然后创建新项目,重写旧程序的所有代码,加载 CURL 库并编译。
程序执行有问题。
分析程序MALLOC异常
这是一段有异常的代码:
char* userpwd = (char*)malloc(strlen(USERNAME)+1+strlen(PASSWORD));
printf("\n malloc %s",userpwd);
strcat(userpwd, (const char*)USERNAME);
strcat(userpwd, ":");
strcat(userpwd, (const char*)PASSWORD);
printf("\n not %s",userpwd);
解释一下这个函数:
首先,我必须构建包含“USERNAME:PASSWORD”的变量。
问题出在 char* userpwd = (char*)malloc(strlen(USERNAME)+1+strlen(PASSWORD));
之后
因为当我打印userpwd的值时,我在字符串前有-或其他字符。
然后是正常的登录不正确或被拒绝。
这是图片:
如果功能没有问题,我可以更改代码:
char userpwd[50];
userpwd="USERNAME";
strcat(userpwd, ":");
strcat(userpwd, "PASSWORD");
printf("\n not %s",userpwd);
还有这个功能。
但程序读取文件 configuration.txt
以获取 URL、USERNAME 和 PASSWORD。
然后用malloc
很方便,但是在我的电脑和我妹妹上,我的字符异常。
如何防止这些异常?为什么我会有这些奇怪的字符? 感谢您的帮助
P.S:为了保护我的账户,我删除了白色的字符串 USERNAME 和 PASSWORD。
最佳答案
您忘记为终止零添加 1。
您还忘记了在将 strcat
添加到字符串之前以零终止字符串。
这会导致未定义的行为。
char* userpwd = (char*)malloc(strlen(USERNAME) + 1 + strlen(PASSWORD) + 1);
userpwd[0] = 0;
或者(更好)使用惯用的 C++:
std::string USERNAME;
std::string PASSWORD;
// Load username and password...
std::string pass = USERNAME + ":" + PASSWORD;
并将pass.c_str()
传递给登录函数
关于c++ - 无法使用 malloc 创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23338976/