Tag: const char

使用malloc()为const char字符串动态分配内存

我正在编写一个从.ini文件中读取值的程序,然后将该值传递给接受PCSTR的函数(即const char *)。 该函数是getaddrinfo() 。 所以,我想写PCSTR ReadFromIni() 。 要返回一个常量字符串,我计划使用malloc()分配内存并将内存转换为常量字符串。 我将能够获得从.ini文件中读取的确切字符数。 这种技术还好吗? 我真的不知道还能做什么。 以下示例在Visual Studio 2013中正常运行,并根据需要打印出“hello”。 const char * m() { char * c = (char *)malloc(6 * sizeof(char)); c = “hello”; return (const char *)c; } int main(int argc, char * argv[]) { const char * d = m(); std::cout << d; // use PCSTR […]

是strtol,strtod不安全吗?

似乎strtol()和strtod()有效地允许(并强制)你在字符串中抛弃constness: #include #include int main() { const char *foo = “Hello, world!”; char *bar; strtol(foo, &bar, 10); // or strtod(foo, &bar); printf(“%d\n”, foo == bar); // prints “1”! they’re equal *bar = ‘X’; // segmentation fault return 0; } 上面,我自己没有演出。 但是, strtol()基本上将我的const char *转换为char *给我,没有任何警告或任何东西。 (事实上​​,它不允许你键入bar作为const char * ,因此强制类型中的不安全更改。)这不是真的很危险吗?