I have been working on a question in c++ but im stuck in a part.
It is a long code but I will only post a small part of it where i am stuck now. Here it is;
char* x = (char*)malloc(sizeof(char));
char y = (char)malloc(sizeof(char));
y = *x;
The problem is when I do it, if X points to a char named “HELLO”, when i print y it only prints ‘H’ letter.
I want to copy the whole word that char* has into a char variable. Also I dont know the sizes of the char’s, because they are given by the user. So the length could be anything. I tried strcpy() but couldnt managed to solve the problem.
Any help appreciated.
**Thanks for all the comments. Now I decided to use std::string according to your comments. And I guess Im never gonna use malloc again. Now I have to go back to code and change everything according to string and check if everything works.
To paraphrase Inigo Montoya, I don’t think this code means what you think it means.
malloc(sizeof(char))This allocates a certain amount of memory. How much memory is allocated is dictated by
malloc‘s parameter. In this case you’re passingsizeof(char)which is, by definition, one byte exactly. Therefore, you are allocating one byte of memory.If you insist on using
malloc(more on this later) then what you should be doing is figuring out how long the string you want to store is, add one more byte for the NULL terminator, and thenmallocthat much. In the case of the stringHello, world.which is 13 characters, the corresponding call would be:malloc(14)Next:
char y = (char)malloc(sizeof(char));mallocreturns a pointer to the memory it allocated for you.yin this case isn’t a pointer, it’s just achar. The two aren’t the same. It compiles and appears to work because you use the bludgeoning tool known as a C-style cast:(char)malloc(...). This tells the compiler, “I know I’m pointing the gun at my foot. Just do what I tell you and don’t complain.” Which it dutifully does. But you’re doing the wrong thing for several reasons:mallocreturns a pointer but you’re trying to cast it to acharyis just acharbut you treat it as if it were a whole string.So if you again insist on using
malloc, you need to do something like this:But, you shouldn’t be using
mallocat all in C++. Instead, you should be usingstd::string:This is better because:
strings manage thier own memory. You don’t leak memory like you did in your code.stringis type-safer. You violated type safety when you cast the return frommallocto achar. You can do it, but its not achar. That’s bad.stringwon’t let you shoot yourself like this without great effort.