c - Unable to understand Malloc output -
#include<stdio.h> #include<stdlib.h> int main() { char *p; p=malloc(1); scanf("%s",p); printf("%s",p); free(p); }
the code takes 27 characters after segmentation fault occurs.can explain unusual behavior of malloc(1)?
you're allocating single byte. segfault fair game @ point after first byte in example. happens 27 bytes you. different every time run program
edit: if mean allocate 1 bye read single character, alter functions to:
scanf(" %c", p); printf("%c", p);
the leading space in front end of character specifier on scanf trick scanf ignoring white space may seek assign buffer (if exists)
c pointers malloc free
No comments:
Post a Comment