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
@Palec scanf("%ms", &foo); is correct. The %ms specifier allocates memory and "returns" a pointer to that memory.
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.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With