JMUP JMUP - 2 months ago 12
C Question

Using pointer destination in strftime (C)

First, the apology: new to C, and fairly green in coding generally.

The problem: trying to create a timestamp in C using strftime().
This works:

#include <time.h>
...
char timestamp[14];
...[code to define timestruct]
strftime(timestamp,15,"%Y%m%d%H%M%S", timestruct);


But this gives a segmentation fault:

#include <time.h>
...
char *timestamp;
...[code to define timestruct]
strftime(timestamp,15,"%Y%m%d%H%M%S", timestruct);


Obviously, I have a solution that works, so basically all is well. But why does the version with
timestamp
as a pointer not work?

Thanks in advance.

Answer

Pointers in C require you to allocate space for them on the heap. In the first case, when you declare char timestamp[14], the 14 in the brackets is telling the compiler to allocate 14 bytes on the stack for timestamp. So you can use it for strings shorted than 14 bytes and you'll be fine.

In the second case, you declare char *timestamp but don't allocate any memory to it. Thus when strftime tries to write to it, it is writing to invalid memory that it doesn't have access to so you get a seg fault. To fix this, you need to allocate memory to timestamp by saying char *timestamp = malloc(14). This will point timestamp to 14 bytes allocated on the heap that it can use. The issue with this method is you have to free the memory manually by calling free(timestamp) after you are done using it.

The first method is preferred if timestamp is a local variable that doesn't need to exist longer than the scope of the function it is in because it will automatically get cleaned up.

Comments