malloc分配的char*在分配函数返回后打印乱码是什么原因?
问题根因
- 核心错误是指针参数的值传递逻辑错误:C/C++中默认参数是值传递,你给
cast_to_cstyle和parse_url传递的char*类型参数,本质上是把外部指针的值拷贝了一份传给函数,函数内部修改target指针本身的赋值(比如target = malloc(...))只会修改函数栈上的局部副本,完全不会影响外部的原始指针。 - 你main函数里的
protocol/hostname等指针自始至终都是未初始化的野指针,你打印的是野指针指向的随机内存内容,自然出现乱码,甚至可能直接触发程序崩溃。 - 额外说明:你malloc分配的堆内存确实还存在,但你把存着堆地址的局部指针变量销毁了,既没法用这块内存,还造成了内存泄漏。
修复方案
你需要给函数传递指针的地址(C兼容写法,用char**)或者指针的引用(C++专属写法,用char*&),让函数内部可以直接修改外部原始指针的值。
这里给出C兼容的修复版本(适配你对接C API的需求):
#include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; // 参数改为char**,接收外部指针的地址 void cast_to_cstyle(string source, char **target) { *target = (char *)malloc(source.size() + 1); memcpy(*target, source.c_str(), source.size() + 1); } // 四个输出参数都改为char**,接收外部指针的地址 void parse_url(string url, char **protocol_cstyle, char **hostname_cstyle, char **port_cstyle, char **path_cstyle) { size_t found = url.find_first_of(":"); string protocol = url.substr(0, found); string url_new = url.substr(found + 3); // `url_new` is the url excluding the "http//" part size_t found1 = url_new.find_first_of(":"); string hostname = url_new.substr(0, found1); size_t found2 = url_new.find_first_of("/"); string port = url_new.substr(found1 + 1, found2 - found1 - 1); string path = url_new.substr(found2); cast_to_cstyle(protocol, protocol_cstyle); cast_to_cstyle(hostname, hostname_cstyle); cast_to_cstyle(port, port_cstyle); cast_to_cstyle(path, path_cstyle); } int main() { char *protocol; char *hostname; char *port; char *path; // 传四个指针的地址到parse_url parse_url("http://www.example.com:80/file.txt", &protocol, &hostname, &port, &path); printf("%s, %s, %s, %s\n", protocol, hostname, port, path); // 用完记得释放堆内存,避免内存泄漏 free(protocol); free(hostname); free(port); free(path); return 0; }
运行后输出结果为:http, www.example.com, 80, /file.txt,符合预期。
内容的提问来源于stack exchange,提问作者Alvin
相关产品推荐
相关产品推荐

