-1

why is the the second sprintf not working?

char* jc;
    char* tn;
    char* result = malloc((256)*sizeof(char));
    int thread=99;
    int jobcounter=88;
    sprintf(jc, "%d", jobcounter);
    sprintf(tn, "%d", thread);
    strcpy(result,"file_");
    strcat(result,jc);
    strcat(result,"_");
    strcat(result, tn);
    strcat(result,".html");
    printf("%s",result);

Output:

file_88_Þ*m.html

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Vor Name
  • 221
  • 1
  • 8

1 Answers1

1

In your case

sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);

causes undefined behavior as none of those pointers (first arguments) point to any valid memory.

You need to make sure that the pointer(s) you're using to access a(ny) memory location points to a valid memory. You can either

  • make them point to statically/automatic allocated variable or
  • use a memory allocator function like malloc() or family.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261