• Advertisement

Archived

This topic is now archived and is closed to further replies.

seg fault on free(), can't figure out why

This topic is 5494 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is a stupid mistake, I''m sure, and I suspect I don''t quite understand what''s going on. I''m compiling with g++ under unix, by the way. I''m using time() and localtime() to get the date for use in a lab project, like so:
time_t seconds;
struct tm* theTime;

time(&seconds);
theTime = localtime(&seconds);
 
No problem, does what it''s supposed to. Then I go to free the memory for theTime - no good. I get a segmentation fault. I tried it with no code inbetween the call to local time and the call to free(), still get a seg fault. What am I missing? Do I not need to free up the memory at all? -Lutrosis

Share this post


Link to post
Share on other sites
Advertisement
You forgot to allocate the tm struct:

struct tm* theTime;

theTime = malloc(sizeof(struct tm));

2DNow - Specializing in yesterday''s technology today!

Share this post


Link to post
Share on other sites
I don''t think that''s it though - localtime returns a (struct tm*) - if I allocate memory for theTime, then assign another value to the pointer via theTime = localtime(), bye bye to the memory I just allocated. I thought localtime was allocating the memory for me (because I don''t see how it would work any other way).

-Lutrosis

Share this post


Link to post
Share on other sites
localtime has a statically allocated array to store the result, and it''s the address of this static array that is returned, and you should not try to free this memory.

However, this means that as soon as you call localtime, any previous tm pointer is invalidated.

Share this post


Link to post
Share on other sites

  • Advertisement