I’m having difficulty learning C language’s malloc and pointer:
What I learned so far:
-
Pointer is memory address pointer.
-
malloc()allocate memory locations and returns the memory address.
I’m trying to create a program to test malloc and pointer, here’s what I have:
#include<stdio.h>
main()
{
char *x;
x = malloc(sizeof(char) * 5);
strcpy(*x, "123456");
printf("%s",*x); //Prints 123456
}
I’m expecting an error since the size I provided to malloc is 5, where I put 6 characters (123456) to the memory location my pointer points to. What is happening here? Please help me.
Update
Where to learn malloc and pointer? I’m confused by the asterisk thing, like when to use asterisk etc. I will not rest till I learn this thing! Thanks!
You are invoking undefined behaviour because you are writing (or trying to write) beyond the bounds of allocated memory.
Other nitpicks:
strcpy(), you are copying 7 bytes, not 6 as you claim in the question.strcpy()is flawed – you are passing acharinstead of a pointer tocharas the first argument.-Wallin your compiler command line.<stdlib.h>formalloc()and<string.h>forstrcpy().int main()(or, better,int main(void)).return(0);at the end ofmain(), even though C99 follows C++98 and allows you to omit it.You may be unlucky and get away with invoking undefined behaviour for a while, but a tool like valgrind should point out the error of your ways. In practice, many implementations of
malloc()allocate a multiple of 8 bytes (and some a multiple of 16 bytes), and given that you delicately do not step over the 8 byte allocation, you may actually get away with it. But a good debuggingmalloc()orvalgrindwill point out that you are doing it wrong.Note that since you don’t
free()your allocated space before you return frommain(), you (relatively harmlessly in this context) leak it. Note too that if your copied string was longer (say as long as the alphabet), and especially if you tried tofree()your allocated memory, or tried to allocate other memory chunks after scribbling beyond the end of the first one, then you are more likely to see your code crash.Undefined behaviour is unconditionally bad. Anything could happen. No system is required to diagnose it. Avoid it!