pointers - Problems with free() function in C -


i have while loop inside for loop handle strings. here structure of code:

char mystring[1000]; //initialize , maybe change mystring for(/*conditions*/){     while(/*conditions*/){         if(strchr(mystring,' ') == null){             break;         }         char *temp = malloc(sizeof(char) * strlen(mystring));         strcpy(temp,mystring);         *strchr(temp,' ') = '\0';         strcat(mystring," ");         strcat(mystring,temp);         free(temp);     } } 

sometimes, code works fine, process ends , returns 3 means there error (3 return value when try use null shouldn't example mypointer->example mypointer null). after tests, found out line causing problem free(temp);. tried replace if(temp != null){free(temp);} didn't change anything. tried declare temp char temp[1000] instead of malloc , take away free(temp); line still same thing. if take away free(temp); line , still use malloc problem solved instead there huge memory leak, can't that. if there error or not depends on in mystring string, means if there value in there, there error, , if there value, there never error, can't manage find out type of values work , ones don't, seems random.

why free(temp); work , not , how can work?

the major problem is, you're allocating 1 element less required memory.

strlen() not account terminating null, you're 1 short of required memory. later, doing

strcpy(temp,mystring); 

is out of bound access (to store terminating null) invokes undefined behavior. result, see

sometimes, code works fine, process ends , returns 3 means there error[....]

to resolve, should modify allocation statement like

char *temp = malloc(strlen(mystring) + 1); // +1 terminating null,                                            // sizeof(char) == 1, guaranteed c standard. 

that said, man page

the strchr() , strrchr() functions return pointer matched character or null if character not found. [...]

and, highlighted scenario,

*strchr(temp,' ') = '\0';

attempts dereference null-pointer constant (null) invalid , again, invokes ub. check valid return value before dereferecing returned pointer


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -