使用printf&scanf的C程序在输入时崩溃

kar*_*421 2 c scanf segmentation-fault

我正在编写以下c代码并收到错误:

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

int main()
{
char *prot;
char addr[20];
FILE *fp;
int i = 0;
int tos,pld;

prot = (char *)malloc(sizeof(char *));
//addr = (char *)malloc(sizeof(char *));

printf("\n enter the protocol for test::");
scanf(" %s",prot);
printf("\n enter the addr::");
scanf(" %s",addr);
printf("\n enter the length of the payload::");
scanf(" %d",pld);
printf("\n enter the tos :: ");
scanf(" %d",tos);
Run Code Online (Sandbox Code Playgroud)

输入值时出现以下错误.有一个分段错误,任何人都可以告诉我为什么会出现这个段错误:

enter the protocol for test::we

enter the addr::qw

enter the length of the payload::12

Segmentation fault
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

prot = (char *)malloc(sizeof(char *));
Run Code Online (Sandbox Code Playgroud)

应该:

prot = malloc(sizeof(char) * SIZE); // SIZE is the no. of chars you want
Run Code Online (Sandbox Code Playgroud)

另一个问题是:你应该使用&整数scanf()!

随着变化:

printf("\n enter the length of the payload::");
scanf(" %d",&pld);
printf("\n enter the tos :: ");
scanf(" %d",&tos);
Run Code Online (Sandbox Code Playgroud)

  • 而且你不应该从malloc转换返回值. (2认同)