Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf dynamic allocation

For whatever 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'm trying to allocate memory for a string dynamically but as I said earlier my program simply outputs (null). I worked around this by making a function using getche and realloc but it seems almost pointless due to the fact that I also had to program what would happen if the user entered backspace, tab, etc.. But as I said that is just a work around and I would rather know why the above code is not working...

Additional Information:

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

like image 562
Keith Miller Avatar asked Aug 13 '12 00:08

Keith Miller


People also ask

Does Scanf allocate memory?

@Palec scanf("%ms", &foo); is correct. The %ms specifier allocates memory and "returns" a pointer to that memory.

Does C allow dynamic memory allocation?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

What does malloc () calloc () realloc () free () do?

Functions malloc, calloc, realloc and free are used to allocate /deallocate memory on heap in C/C++ language. These functions should be used with great caution to avoid memory leaks and dangling pointers.

How do you dynamically allocate?

To allocate space dynamically, use the unary operator new, followed by the type being allocated. These statements above are not very useful by themselves, because the allocated spaces have no names!


1 Answers

I am not seeing %m in section 7.21.6.2 of the Draft C11 standard (the section on fscanf). I suggest that you avoid it and call malloc() as you would in C99.

like image 192
Norman Ramsey Avatar answered Oct 13 '22 21:10

Norman Ramsey