没有分段错误可访问超出范围的内存 [英] No segmentation fault for accessing out of bound memory
问题描述
我的英语说得不好.
所以在我的程序中,我想将txt文件中存在的文本复制到数组中.
so in my program I want to copy a text who exists in a txt file to an array.
typedef struct Chaine
{
char * Lachaine;
int Taille_C;
} Chaine ;
int main (void)
{
Chaine *Tab_Texte=NULL;
Tab_Texte=(Chaine*)malloc(sizeof(Chaine));
FILE* Texte= NULL;
Texte = fopen("chaines", "r");
fseek(Texte, 0, SEEK_END);
Tab_Texte->Taille_C=ftell(Texte);
fseek(Texte, 0, SEEK_SET);
Tab_Texte->Lachaine=NULL;
Tab_Texte->Lachaine=(char*)malloc(sizeof(char)*Tab_Texte->Taille_C);
fread(Tab_Texte->Lachaine,sizeof(char)*(Tab_Texte->Taille_C),1,Texte);
printf("%s",Tab_Texte->Lachaine);
return 0;
}
这里一切都很好,当我改变时
Here everything works great and when I change
Tab_Texte->Lachaine=(char*)malloc(sizeof(char)*Tab_Texte->Taille_C);
带有(例如)
Tab_Texte->Lachaine=(char*)malloc(sizeof(char)*Tab_Texte->Taille_C - 10);
它始终有效,它想向我展示一个分段错误,因为 sizeof(char)* Tab_Texte-> Taille_C-10
短于 sizeof(char)* Tab_Texte->Taille_C
,而不是文件中的文本.
It works always, It suppose to show me a segmentation fault because sizeof(char)*Tab_Texte->Taille_C - 10
is shorter than sizeof(char)*Tab_Texte->Taille_C
so than the text in the file.
你能告诉我为什么它总是有效吗?
Can you tell me why it always works?
推荐答案
您遇到的事情称为未定义行为.
- 访问已分配的内存
- 使用非空终止的char数组作为字符串
- 提供了无效的文件指针
所有这些[任何]都将导致不确定的行为,并且副作用可能是细分错误,但不能保证.
all [any] of these will result in undefined behavior and the side effect may be a segmentation fault, but it's not guaranteed.
请
- 在使用返回的指针之前检查
fopen()
是否成功 - 以null终止char数组以将其用作字符串 使用结束后,
-
free()
分配的内存. - 请勿转换
malloc()
/calloc()
的返回值.
- Check for the success of
fopen()
before using the returned pointer - null-terminate a char array to use it as a string
free()
the allocated memory after the usage is over.- Do not cast the return value of
malloc()
/calloc()
.
这篇关于没有分段错误可访问超出范围的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!