Been solving leetcode puzzles and thought I solved this one pretty quickly, yet I am running into a strange error. My output is matching the expected output, so I have no idea why it's rejecting my solution based off the following test case.
char* reverseString(char* s)
{
/* Sample input: "Hello"
Sample output: "olleh"
*/
char * reversed_string;
char temp[1];
int length = 0;
int i;
if(s == NULL)
return NULL;
length = strlen(s);
/* While string is not null, increment pointer */
while(*s != NULL)
{
s = s + 1;
}
/* Allocate reversed string based off length of original string */
reversed_string = malloc(length + 1);
/* Traverse backwards for length of string */
/* Copy each letter to temp */
/* Concatenate each letter to reversed_string */
for(i = 0; i < length; i++)
{
s = s - 1;
strncpy(temp, s, 1);
strcat(reversed_string, temp);
}
reversed_string[length] = '\0';
/* Return reversed string */
return reversed_string;
}
MOutput = My Output
EOutput = Expected Output
Input: "?CZU.9Iw8G3K?fse,b7 m;0?f :`c9d!D'`Pem0'Du0;9i` 03F,: 7,oPw'T'5`1g!iwR5J71iJ\"f;r6L;qZaDGx?cvkS 8\"UY2u`YC P3CM y`4v 1q7P;Zd1.;:RA!oYh;!2W8xMfMx8W2!;hYo!AR:;.1dZ;P7q1 v4`y MC3P CY`u2YU\"8 Skvc?xGDaZq;L6r;f\"Ji17J5Rwi!g1`5'T'wPo,7 :,F30 `i9;0uD'0meP`'D!d9c`: f?0;Z 7b,esf?K3G8wI9.UmC?"
MOutput: "?CmU.9Iw8G3K?fse,b7 Z;0?f :`c9d!D'`Pem0'Du0;9i` 03F,: 7,oPw'T'5`1g!iwR5J71iJ"f;r6L;qZaDGx?cvkS 8"UY2u`YC P3CM y`4v 1q7P;Zd1.;:RA!oYh;!2W8xMfMx8W2!;hYo!AR:;.1dZ;P7q1 v4`y MC3P CY`u2YU"8 Skvc?xGDaZq;L6r;f"Ji17J5Rwi!g1`5'T'wPo,7 :,F30 `i9;0uD'0meP`'D!d9c`: f?0;m 7b,esf?K3G8wI9.UZC?"
EOutput: "?CmU.9Iw8G3K?fse,b7 Z;0?f :`c9d!D'`Pem0'Du0;9i` 03F,: 7,oPw'T'5`1g!iwR5J71iJ"f;r6L;qZaDGx?cvkS 8"UY2u`YC P3CM y`4v 1q7P;Zd1.;:RA!oYh;!2W8xMfMx8W2!;hYo!AR:;.1dZ;P7q1 v4`y MC3P CY`u2YU"8 Skvc?xGDaZq;L6r;f"Ji17J5Rwi!g1`5'T'wPo,7 :,F30 `i9;0uD'0meP`'D!d9c`: f?0;m 7b,esf?K3G8wI9.UZC?"
Anyone spot what might be wrong with my function? Is there undefined behavior anywhere?
char temp[1]tochar temp[2], as you need an additional entry for the null-character.temp[1] = '\0';afterstrncpyjust to get it to compile.ninstrncpy. However, the following call tostrcatis done with a non-null-terminated string, which is where the problem lies.temp[1] = '\0';!!!temp[1] = '\0';