I'm new to C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void demo() {
char* s = malloc(10);
strcpy(s, "foo");
free(s);
}
int main()
{
demo();
}
Will this program leak memory with several bytes?
I'm new to C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void demo() {
char* s = malloc(10);
strcpy(s, "foo");
free(s);
}
int main()
{
demo();
}
Will this program leak memory with several bytes?
Will this program leak memory with several bytes?
No.
free(s)
will de-allocate all the memory that was dynamically allocated by char* s = malloc(10);
in this example.
As @Alexander commented: "Is your concern about the last 6 characters of s
? (past the end of "foo"
) Worry not, free()
will free the whole allocation of s
, regardless of how you used it or what you put in it"
Good read: What is a memory leak?
The function malloc is declared the following way
void *malloc(size_t size);
It knows nothing about how the allocated memory will be used and what will be stored in it.
The only parameter size
specifies the size of the allocated memory.
To free the allocated memory all you need is to pass the pointer to the allocated memory.
So there is neither memory leak in this code snippet
char* s = malloc(10);
strcpy(s, "foo");
free(s);
The pointer s
is point to the allocated memory and this pointer is used to free the allocated memory. And it is entirely unimportant whether something was stored in the allocated memory or not.
If you want to reduce or enlarge the allocated memory when use another standard C function realloc
. The function keeps the data stored in the previously allocated memory according to the newly allocated size of the extent of memory.
For example, you could write
char* s = malloc(10);
const char *foo = "foo";
strcpy( s, foo );
size_t n = strlen( s );
char *tmp = realloc( s, n + 1 );
if ( tmp != NULL ) s = tmp;
puts( s );
free( s );