I’m fairly competent in a few scripting languages, but I’m finally forcing myself to learn raw C. I’m just playing around with some basic stuff (I/O right now). How can I allocate heap memory, store a string in the allocated memory, and then spit it back out out? This is what I have right now, how can I make it work correctly?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *toParseStr = (char*)malloc(10);
scanf("Enter a string",&toParseStr);
printf("%s",toParseStr);
return 0;
}
Currently I’m getting weird output like ‘8’\’.
Firstly, the string in
scanfis specifies the input it’s going to receive. In order to display a string before accepting keyboard input, useprintfas shown.Secondly, you don’t need to dereference
toParseStrsince it’s pointing to a character array of size 10 as you allocated withmalloc. If you were using a function which would point it to another memory location, then&toParseStris required.For example, suppose you wanted to write a function to allocate memory. Then you’d need
&toParseStrsince you’re changing the contents of the pointer variable (which is an address in memory — you can see for yourself by printing its contents).As you can see, it accepts
char ** ptr_stringwhich reads as a pointer which stores the memory location of a pointer which will store the memory address (after themallocoperation) of the first byte of an allocated block ofnbytes (right now it has some garbage memory address since it is uninitialized).Thirdly, it is recommended to free memory you allocate. Even though this is your whole program, and this memory will be deallocated when the program quits, it’s still good practice.