yarokas
yarokas

Reputation: 39

Segmentation fault in snprintf() c

Im trying to create a function with return a char * with the current date and time. But im getting the segmentation fault while usig snprintf. Here's the part of the code.

int buf_size = 20;
char *n = NULL;
snprintf(n, buf_size , "%d-%d-%d %d:%d:%d\n", 1900+st.tm_year,
         st.tm_mon+1, st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec);

Upvotes: 0

Views: 4339

Answers (4)

chux
chux

Reputation: 153498

After accept answer.

Let snprintf() determine buffer size.

int buf_size = snprintf(NULL, 0 , "%d-%d-%d %d:%d:%d\n", 1900+st.tm_year,
     st.tm_mon+1, st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec);
if (buf_size < 0) {
  Hanlde_EncodingError();
}

char n[buf_size + 1];  // or char *n = malloc(buf_size + 1);

snprintf(n, buf_size , "%d-%d-%d %d:%d:%d\n", 1900+st.tm_year,
     st.tm_mon+1, st.tm_mday, st.tm_hour, st.tm_min, st.tm_sec);

Upvotes: 0

zwol
zwol

Reputation: 140589

snprintf does not allocate the buffer for you. You set n to NULL, so it cheerfully tries to write to a nonexistent memory location and crashes.

You want to use asprintf instead. If your C library does not have asprintf, it can be implemented using malloc and snprintf. I leave doing that as an exercise.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You need to allocate memory that would be pointed to by pointer p and where you are going to write data.

Instead of

char *n = NULL;

you should write

char *n = malloc( buf_size );

Upvotes: 1

Bob Kaufman
Bob Kaufman

Reputation: 12815

n is NULL, so you're attempting to copy to an invalid memory location.

Consider replacing the second line with

char n[80]; /* at least enough characters for the buffer */

or, more suitable for returning a string

char *n = ( char * ) malloc( 80 * sizeof( char ) );

Upvotes: 2

Related Questions