Your problem is your placement of free(copy)
, move it after you make use of copy
, otherwise you are attempting to read from a variable that has already been freed
(an uninitialized value – invoking Undefined Behavior), (as @Pras correctly notes you free (copy)
, not free (origin)
, e.g.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
char *copy;
char *origin = "tutorialspoint";
copy = malloc (strlen (origin) + 1);
strcpy(copy, origin);
printf("string = %s, Address = %p\n", copy, (void *)copy);
printf("origin = %s, Address = %p\n", origin, (void *)origin);
free(copy); /* works find here */
return(0);
}
note: use of %p
for the pointer address.
You should also validate ALL memory allocations, e.g.
if (!(copy = malloc (strlen (origin) + 1))) {
fprintf (stderr, "error: virtual memory exhausted.\n");
return 1;
}
Example Use/Output
$ ./bin/origin
string = tutorialspoint, Address = 0xbe3010
origin = tutorialspoint, Address = 0x400710
copy is freed
Continuing from your comment, copy
is in fact freed. How can you tell? You run you code through a memory/error checking program like valgrind
, e.g.
$ valgrind ./bin/origin
==10564== Memcheck, a memory error detector
==10564== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10564== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==10564== Command: ./bin/origin
==10564==
string = tutorialspoint, Address = 0x51d8040
origin = tutorialspoint, Address = 0x400710
==10564==
==10564== HEAP SUMMARY:
==10564== in use at exit: 0 bytes in 0 blocks
==10564== total heap usage: 1 allocs, 1 frees, 15 bytes allocated
==10564==
==10564== All heap blocks were freed -- no leaks are possible
==10564==
==10564== For counts of detected and suppressed errors, rerun with: -v
==10564== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
As you can see, all memory allocated had in fact been freed and — no leaks are possible and there were 0 errors from 0 contexts.
6
solved In c program, why free memory of string (which copy from strcpy) in osx is not woking? [duplicate]