String Padding in C

前端 未结 10 1521
迷失自我
迷失自我 2020-11-28 22:25

I wrote this function that\'s supposed to do StringPadRight(\"Hello\", 10, \"0\") -> \"Hello00000\".

char *StringPadRight(char *string, int padded_len, char          


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 22:53

    The argument you passed "Hello" is on the constant data area. Unless you've allocated enough memory to char * string, it's overrunning to other variables.

    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    strncpy(buffer, "Hello", sizeof(buffer));
    StringPadRight(buffer, 10, "0");
    

    Edit: Corrected from stack to constant data area.

提交回复
热议问题