Dynamic allocation scanning

For some reason, the following code prints (null):

#include <stdio.h> #include <stdlib.h> int main(void) { char *foo; scanf("%ms", &foo); printf("%s", foo); free(foo); } 

I am trying to allocate memory for a string dynamically, but as I said earlier, my program just outputs (null). I worked on this by executing a function using getche and realloc, but this seems almost pointless due to the fact that I also had to program what happens if the user enters backspace, tab, etc. But, as I said, this is just a job and I would rather know why the code above does not work ...

Additional Information:

I am using Pelles C IDE v7.00 and compiling with the C11 standard

+6
source share
4 answers

I do not see %m in section 7.21.6.2 Draft C11 standard ( fscanf section). I suggest you avoid this and call malloc() just like on C99.

+9
source

% m is a GNU extension, so it is not available in Pelles C.

0
source

I am using Linux 3.2.0 amd 64 with gcc 4.7.2 . Using the code:

 char *s; scanf("%ms", &s); printf("%s", s); free(s); 

works fine but doesn't accept spaces.

For static distribution, you can use instead:

 char s[100]; printf("Enter string (max 99 characters): "); scanf("%100[^\n]s", &s); printf("You entered: %s\n", s); 

Hope this helps!

0
source

as Arun says this decision is correct, and Meninx's opinion is incorrect:

 char *s; scanf("%ms", &s); printf("%s", s); free(s); 

I read "man scanf", it says:

Optional character "m". This is used to convert strings (% s,% c,% [),
and frees the caller from having to allocate the appropriate buffer for hold on: instead, scanf () allocates a buffer of sufficient size and assigns the address of this buffer to the corresponding pointer an argument that should be a pointer to a char * variable (this variable does not need to be initialized before the call). The caller must then free (3) this buffer when it is no longer needed.

0
source

Source: https://habr.com/ru/post/922693/


All Articles