我試圖做一個函數,它將'.'
字符放在數組的每個字符串中,以完成它們到n
個字符。 它工作正常,除了我不能複製tmp
sting到數組中的字符串既沒有strcpy,也沒有指針。 的代碼是:strcpy在字符串數組
void foo (char **t, int count, int n) {
int max = 0, i, j;
char *tmp;
for (i = 0; i < count; i++) {
if (max < strlen (t[i])) max = strlen (t[i]);
}
if (max > n) return;
for (i = 0; i < count; i++) {
int diff = n - strlen (t[i]);
tmp = (char *) malloc (diff * (sizeof (char) * n + 2));
for (j = 0; j < diff; j++) {
tmp [j] = '.';
}
tmp [j] = '\0';
strcat (tmp,t[i]);
t[i] = (char *) realloc (t[i], strlen (tmp) + 10);
strcpy (t[i], tmp);
//*(t + i) = *tmp; <- I tried this method too
free (tmp);
}
}
所以運行良好(符連接兩個字符串),直到strcpy (t[i], tmp);
命令。 我在做什麼錯?
(我知道,我保留不必要的大空間,我這樣做是可以肯定的。)
的main()
功能,我使用它是:
int main()
{
char *t[3] = {"string", "foo", "help"};
int i;
foo(t, 3, 10);
for (i = 0; i < 3; ++i)
printf("%s\n", t[i]);
return EXIT_SUCCESS;
}
它沒有給出編譯錯誤,也不警告。
運行時崩潰,並返回-1073741819(0xC0000005),不打印任何內容。
我正在使用CodeBlocks。
'strcpy'是不安全的,因爲它可以通過緩衝區溢出來利用。 – arboreal84
很可能t數組沒有足夠的空間來保存結果。 –
@ arboreal84如果你可以證明它的第二個參數是以'\ 0'結尾並且它的第一個參數有足夠的空間,那麼'strcpy'是完全安全的。 't [i] =(char *)realloc(t [i],strlen(tmp)+ 10);'表明情況是這樣的。 –