I have the code block below, I deleted all unnecessary parts, just left the problematic part. My purpose to fetch the time in a specific format that I need(YYYYMMDDHHmm) by fetch_time function. In order to return char array, I used malloc. However, the program crashes if I run the code below like a minute. When I monitor run-time of the code by a debugging tool, the memory location that p1 points increases e.g 0x72120 for the first iteration, 0x72150 for the second iteration, and so on. So, I suspect it fails because of the memory problem. I wonder what do I do wrong and how can I solve the problem?
Btw, I guess I can solve the problem by defining a global char array and assining the time info in the sub-function. I would like to learn my mistake in the malloc usage and learn the solution. Thank you.
int main(int argc,char *argv[]){
char timedate2[13];
char *p1 = malloc(strlen(timedate2)+1);
if(!p1){exit(1);}
while(1){
p1=fetch_time();
}
}
char *fetch_time() {
char *p;
time_t rawtime;
struct tm * timeinfo;
char buffer [13];
time ( &rawtime );
timeinfo = localtime ( &rawtime );
strftime (buffer,13,"%04Y%02m%02d%02k%02M",timeinfo);
p = (char *)malloc(sizeof(buffer));
strcpy(p, buffer);
return p;
}
The code looks correct per see. There’s one catch thought. When you call
malloc, you are requesting some amount of memory in which you store your date string. Everytime you callfetch_timeyou will request some (other) piece of memory with a new string. You never re-use the same piece of memory and eventually run out of memory. To fix that, you need to free every piece of memory you requested which will allow the system to eventually reuse it again.Also, please fix the indentation.
If you find similar problems in the future, consider using a tool like
valgrind, it will help you a lot (google it up!).