#Why is this char array being set to null after scanf?

9 messages · Page 1 of 1 (latest)

shrewd prawn
#

Hi! I have this:

    char taskCompleteUrl[22] = "tasks/";
    char taskID[10];
    scanf("%s", taskID);
    strcat(taskCompleteUrl, taskID);
    strcat(taskCompleteUrl, "/close");
    printf("%s\n", taskCompleteUrl);

Assuming the user enters 1234567890, printf outputs 1234567890/close, when I expect it to output tasks/1234567890/close. Why is this?

If I remove the line with scanf and manually set taskID equal to 1234567890, I get this string: tasks/1234567890tasks/1/close as well as a stack smashing error (which is similar to stack overflow, I think?)

north cometBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

shrewd prawn
#

I forgot about the null character. Oops. (I.e, taskID[10] should've been taskID[11])

jagged ether
#

also such program will be always at risk, so if you have taskdID[11], then you should at least use %10s if you like scanf

shrewd prawn
#

Duly noted. Are there any better options?

jagged ether
#

I would use fgets

shrewd prawn
#

Ok, thank you!

#

!solved