avinashse
avinashse

Reputation: 1460

Strange Working of sprintf

#include<stdio.h>
#include<time.h>
int main(){
  char filepath[100];
  char datevar[15];
  char command[30];
  struct tm *t1;
  time_t now ;
  time(&now);
  memcpy(&t1,localtime(&now),sizeof(t1));
  t1 = localtime(&now);
  memset(filepath,0,sizeof(filepath));
  sprintf(datevar,"%04d%02d%02d",t1->tm_year+1900,t1->tm_mon+1,t1->tm_mday);
  strcpy(filepath,"abc");
  strcat(filepath,"/xyx/");
  strcat(filepath,datevar);
  strcat(filepath,"/");
  printf("filepath  1:- %s\n",filepath);
  sprintf(command, "hello %s good path",filepath);
  printf("filepath  2:- %s\n",filepath);
  return 0;
}

In the above program, both printf is printing different filepath. output which I am getting :-

filepath  1:- abc/xyx/20130430/
filepath  2:- h

My question is why filepath is changed if I am using it in sprintf.

Upvotes: 0

Views: 1112

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409166

Unrelated to this problem, but you have an even more serious problem and that is this:

memcpy(&t1,localtime(&now),sizeof(t1));

Here you use &t1, which takes the address of the pointer, meaning you pass to memset a pointer to a pointer to a struct tm, in other words struct tm **. You also use sizeof(t1) which is the size of the pointer and not what it might point to, and depending on platform it will be four or eight bytes.

Since you directly afterward do

t1 = localtime(&now);

The memset call isn't actually needed.

Upvotes: 3

Daniel Fischer
Daniel Fischer

Reputation: 183878

It's because

char command[30];

is not large enough to accommodate

sprintf(command, "hello %s good path",filepath);

It looks as though the final 'h' and the 0-terminator go into filepath. (Which is coincidental, sincesprintfing more intocommand` than it can hold invokes undefined behaviour.)

Upvotes: 6

Related Questions