strcat

Hi,

I have the question below:
Explain what is wrong with the following code:
1
2
char sms[] = "Gr8",
strcat(sms, " &  )"),


NB
strcat concatenates " & )" to the end of sms

I am correct in saying that sms[] will only hold 4 characters including the \0 terminator so " & )" will overwrite these when concatenated?

Thanks
You have the right idea, but not quite right. The operation will attempt to write the additional characters into the memory immediately following the sms[] array, resulting in corruption of some other data - and unpredictable consequences.
Array sms indeed is allocated as having four elements. Function strcat writes to the end of a character array starting from the terminating zero byte. However array sms has no allocated memory after the terminating zero. So strcat will overwrite memory that does not belong to sms.

You could write the following way

1
2
char sms[9] = "Gr8",
strcat(sms, " &  )"),
Thanks so much guys. The q is just to find what is wrong with it but it is good to know what will fix it if it comes up in the examination that I am preparing for.

Thanks
Topic archived. No new replies allowed.