C - Yet another strtok() and free() issue -
i trying understand how free memory after calls strtok(). read of answered questions here , none seemed address point of confusion. if duplicate feel free point me direction of answers question
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char * aliteral = "hello/world/fine/you"; char * allocatedstring; char * token; int i=0; allocatedstring=(char *) malloc(sizeof(allocatedstring)*21); allocatedstring=strcpy(allocatedstring,aliteral); token = strtok(allocatedstring, "/"); token = strtok(null, "/"); token = strtok(null, "/"); token = strtok(null, "/"); printf("%s\n",allocatedstring); printf("%s\n",token); free(allocatedstring); return 0; } freeing allocatedstring here frees string first \0 character replaced strtok's delimiter. clears until "hello". checked using eclipse debugger , monitoring memory addresses.
how clear rest of it? tried 2 things, having 1 pointer point start of allocatedstring , freeing (didnt work) , freeing token after call strtok() (didnt work either)
so how clean parts of allocatedstring between \0 's ?
edit : clarify, seeing memory address blocks in eclipse debugger, seeing string "hello world fine you" in memory blocks allocated call malloc. after call free(), blocks containing "hello" , first \0 turned gibberish, rest of blocks kept characters "fine you". assumed meant not freed.
free has no knowledge of \0 terminated strings.
free free allocated malloc, , should work in situation.
if evidence free not working string data still exists, misunderstand free.
not 0 out memory. marks available use.
original data remains in memory. memory may allocated next caller of malloc, , caller able overwrite data @ will, because don't own data anymore!
if want memory cleared (such as, if contains password or security key), you must clear out memset, before call free.
again, free marks memory "unallocated, available use malloc", , not clear out contents.
ps debugging systems, such visual studio, overwrite freed data, make obvious in debugger has been freed. behavior not contractually needed in c, , aids in debugging. typically, freed memory may filled 0xdeadbeef.
Comments
Post a Comment