[英]Strcpy just crashes the second time I use in the same context
該代碼等待用戶輸入的字符串,然后程序應立即在指針數組中對它進行排序。
問題是在cop<0
的情況下。 我不知道strcpy()
有什么問題。 如果有人可以幫忙,我會很感激。
這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lecture(char* t[],int len_t); // reads the strings
void ecriture(char* [],int len_t); // prints the strings
int main(int argc, char *argv[], char *envp[])
{
char* cTab[20]={NULL};
int iNbl;
iNbl=lecture(cTab,20); // returns number of strings
puts("");
ecriture(cTab,iNbl); // prints the strings
return 0;
}
int lecture(char* t[],int len_t)
{
char cChaine[80]; // place to make the string in
puts("the String is : ");int i=0;
while(strcmp(gets(cChaine),"end")) // if cChaine==end then it quits
{
int verif=0; // verification to know if the string took its place or not
t[i]=(char *)malloc(strlen(cChaine)+1);
if(i==0)
{
strcpy(t[i],cChaine); puts("case i=0"); //puts is just a verification
}
else
{
int j=0, cop=0;
for(j=0;j<i-1;j++)
{
cop=strcmp(cChaine,t[j]);
if(cop>0)
{
continue;/* after that I will use "verif" to decide if I add the string in the end or in the beginning */
}
if(cop==0)
{
puts("Beginning cop=0 !");
int compteur=0;char* tTmp[20];
for(compteur=j+1;compteur<i;compteur++)
{
strcpy(tTmp[compteur],t[compteur]); //works here as expected;
}
strcpy(t[j+1],cChaine); //here to o_o it's works as I wanted
compteur=0;
for(compteur=j+1;compteur<i;compteur++)
{
strcpy(t[compteur+1],tTmp[compteur]); //works as expected
}
puts("End of cop=0");
verif=1; //to not add the string in the end of t[] cuz it's already added
}
if(cop<0)
{
puts("Beginning of case : cop <0 !");
int compteur=0;char* tTmp[20];
for(compteur=j;compteur<i;compteur++)
{
strcpy(tTmp[compteur],t[compteur]); //it crashes here I don't know why
}
strcpy(t[j],cChaine); // crash ..
compteur=0;
for(compteur=j;compteur<i;compteur++)
{
strcpy(t[compteur+1],tTmp[compteur]); //crash ...
}
}
verif=1;
break;
}
printf("Fin \n");
}
if(verif==0) //the use of verif is here
{
puts("verif =0 :p ");
strcpy(t[i],cChaine); // here is the last case of the array
}
i++;
}
return i;
}
void ecriture(char* t[],int len_t)
{
int i=0;
puts("Lecture ... : ");
for(i=0;i<len_t;i++)
{
puts(t[i]);
}
}
如我所見,這里的問題在於
char* tTmp[20];
在使用like之前,您從未將內存分配給tTmp[n]
strcpy(tTmp[compteur],t[compteur]);
使用未初始化的內存會導致未定義的行為 。
注意:不要被UB的奇怪行為所欺騙。 您的cop == 0
情況與cop < 0
情況同樣是錯誤的。
那就是
gets()
,而要使用fgets()
。 int main(int argc, char *argv[], char *envp[])
不正確。 推薦的簽名是int main(int argc, char *argv[])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.