Reputation: 59
here's the code: can anyone explain this issue how can i deallocate the memory of s in main
char *get(int N)
{
char *s=malloc(10*sizeof(char));
s="hello";
return s;
}
int main()
{
char *s=get(4);
printf(s);
free(s);
}
Upvotes: 1
Views: 801
Reputation: 24726
A variable of type char *
is a pointer (memory address) to a character. In C, it is customary to implement strings as zero-terminated character arrays and to handle strings by using variables of type char *
to the first element of such an array.
That way, variables of type char *
do not actually contain the strings, they merely point to them.
For this reason, the line
s="hello";
does not actually copy the contents of the string, but rather only the pointer (i.e. the memory address) of the string.
If you want to copy the actual contents of the string, you must use the function strcpy instead.
By overwriting the pointer that you use to store the address of the memory allocated by malloc
, you are instead passing the address of the string literal "hello"
to free
. This should not be done. You must instead only pass memory addresses to free
that you received from malloc
.
Upvotes: 0
Reputation: 67476
You have two bugs here:
You reassign the pointer s
with the reference of the string literal "hello", loosing the memory allocated by malloc
You allocate not enough space for the "hello" string. You need at least 6 characters (not 4)
Upvotes: 0
Reputation: 16876
This here:
s="hello";
Doesn't write "hello"
to the allocated memory. Instead, it reassigns s
to point to a read-only place where "hello"
is stored. The memory you allocated with malloc
is leaked, and the free(s);
is invalid, because you can't free that read-only memory.
If you want to copy "hello"
into s
, try strcpy(s,"hello");
instead.
Upvotes: 6
Reputation: 134286
By doing
s="hello";
you're overwriting the returned pointer by malloc()
with the pointer to the first element of the string literal "hello"
, which is not allocated dynamically.
Next, you are passing that pointer (to a string literal) to free()
, which causes the undefined behavior.
You may want to change the assignment to
strcpy(s, "hello");
Additionally, by overwriting the originally returned pointer by malloc()
, you don't have a chance to deallocate the memory - so you also cause memory leak.
Upvotes: 1