malloc
allocates a block of uninitialized, contiguous memory of the requested size in bytes and passes back a
void*
pointer since it has no idea what you want that memory for.
So, how do we calculate how many bytes we need then? Well, in this instance we have an array of characters, so we need space for each element (
char
) and the overall string size. To get the size of the element, we can use
sizeof(char)
. To get the overall array size, we can use
strlen(name) + 1
.
This is your code:
(char*)malloc(strlen(name))
You see the issue? If you put a breakpoint at the
printf
line and look at the lunches[2] structure you'll see the name followed by random garbage because there isn't a null-termination character. This is why we need that +1 on both the
malloc
and
memcpy
to allocate space for the string terminator and to copy it, respectively.
Also you're getting lucky that the size of a
char
is a single byte, otherwise your
malloc
wouldn't allocate the correct size. Generally speaking, you want to get in the habit of doing it like
malloc(sizeof(char) * (strlen(name) + 1))
. It will lead to less headaches down the road (a
char
isn't always 1 byte). The "+1" won't be needed, for example, with an integer array though -
malloc(sizeof(int) * arraySize)
.
This has nothing to do with your memory access problem though. That is caused by
free(name);
name = NULL;
You only
free
what you
malloc
.
name
is stack-allocated. It will be discarded when the stack-frame is popped on function exit. This is also why the line
name = NULL;
should show an error in your compiler. You can't re-assign
name
. It isn't a pointer to a char array,
it is the char array. Did you mean to
free
the structure's name but accidentally referenced the local name instead?