使用malloc()创建字符数组时引发异常

时间:2019-02-05 13:27:46

标签: c

从本质上讲,我正在尝试创建一个程序,该程序仅使用来自用户的输入,然后使用动态分配的内存将其打印出来。是的,我知道如何以简单的方式执行此操作,但是我正在尝试掌握C语言中内存管理的复杂性。那么这段代码有什么问题呢?它运行没有错误,但是当我在命令行中输入字符串时,它将停止工作并在十六进制地址处引发异常。先感谢您。

int main() {
  char *input;

  input = (char *)malloc(20 * sizeof(char)); 
  puts("Enter the string you wish to display"); 
  scanf_s("%s", input); 
  printf_s("%s", *input); 
  free(input);  
  return 0; 
}

3 个答案:

答案 0 :(得分:2)

您的编译器应警告您有关此行的信息:

printf_s("%s", *input);

如果没有,则需要启用“所有警告”设置。 (在gcc和clang上,在命令行中添加-Wextra。)

基本上,参数类型(char)和格式字符串(const char*所期望的类型之间不匹配。 *input取消引用字符指针,因此求值为字符串中的第一个字符。 "%s"需要一个指针,该指针指向以nul结尾的字符数组。

如果您删除*,它应该可以工作:

printf_s("%s", input);

答案 1 :(得分:1)

您可能想要这样:

#include <stdio.h>
#include <stdlib.h>

int main() {
  char *input;

  input = malloc(20 * sizeof(char)); // (char *) is not needed here (but doesn't harm either)
  puts("Enter the string you wish to display");
  scanf("%s", input);
  printf("%s", input);  // *input is wrong here
  free(input);
  return 0;
}

不要使用_s版本,因为它们并不是每个平台上都标准的,或多或少毫无意义,只需使用scanfprintf

答案 2 :(得分:1)

您错误地使用了scanf_s("%s", ...

the docs的逐字记录:

  

安全性更高的功能(具有 _s 后缀)与其他版本之间的主要区别在于,安全性更高的功能要求每个 c 的字符大小, C s S [”类型字段作为紧随变量之后的参数传递。

因此,如果input指向20个char序列的第一个字符,则应为:

  scanf_s("%s", input, 20); 

经验教训:如有疑问,(重新)阅读文档!