c - 指针的内存分配适用于固定变量分配的字符串,但不适用于用户输入字符串
问题描述
例如,给定程序适用于代码中固定的字符串
char str[100] = "With fixed string this code works"
// Output of the program is "fixed string this code works"
但是一旦我使用str
输入
scanf("%s", &str);
似乎在内存分配中发现了错误,因为在给出输入后代码返回错误值。
完整代码如下
int main (void) {
char str[100];
char *p = (char *)malloc(sizeof(char) * str[100]);
printf("Enter something: ");
scanf("%s", &str);
*p = str;
p = strchr(str, ' ');
puts(p + 1);
// Check for the first space in given input string if found then
while (*p++)
if (*p == ' ' && *++p)
printf("%s", *p);
printf ("\n\n");
return 0;
}
不确定在使用scanf
函数输入字符串时是否需要动态内存分配任何其他分配过程
解决方案
你malloc
有一个错误:
char *p = (char *)malloc(sizeof(char)*str[100]);
让我们先简化一下。
不要强制转换malloc
(请参阅:我是否强制转换 malloc 的结果?):
char *p = malloc(sizeof(char)*str[100]);
sizeof(char)
(根据定义)在所有架构上始终为1 ,无论它占用多少位,所以我们可以消除它:
char *p = malloc(str[100]);
现在我们有:
char str[100];
char *p = malloc(str[100]);
你有未定义的行为。str
没有值(即未初始化),并且您传递的元素是数组末尾之后的元素,因此您有未定义的行为。
因此,传递给的长度参数malloc
是随机的。
推荐阅读
- java - Spring Webflux 如何在不阻塞的情况下顺序调用 2 个不同的服务?
- swift - Equivalent of a popover in SpriteKit
- php - Apache 2.4, PHP 7.4.7, Windows 10 can't load cURL Extension from Apache Service but loads fine from Command Line with httpd
- node.js - 404 error when connecting to IP address but not in domain name
- python - pywinauto: get URL from MS Edge Canary Address Bar
- python - tkinter filedialog save and docx tpl
- python - Need to reference a variable before it is called in Python Flask
- wso2 - WSO2 IS - Analytics : `Error while SSL handshake` error
- c# - I'm pretty new to linq lambda. I have a MySQL query.which I need to convert to a lambda query
- c++ - How to run SSH with system() in C++