Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program using printf & scanf crashes on input

I am writing following c code and getting an error :

#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);

I am getting the following error while entering the value.There is a segmentation fault coming could anyone tell me why this segment fault is coming:

enter the protocol for test::we

enter the addr::qw

enter the length of the payload::12

Segmentation fault
like image 436
karan421 Avatar asked Mar 18 '26 21:03

karan421


1 Answers

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

Should be:

prot = malloc(sizeof(char) * SIZE); // SIZE is the no. of chars you want

Another problem is: You should use & for integers in scanf()!

With changes:

printf("\n enter the length of the payload::");
scanf(" %d",&pld);
printf("\n enter the tos :: ");
scanf(" %d",&tos);
like image 127
P.P Avatar answered Mar 21 '26 10:03

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!