c - C中的分配问题和奇怪的行为
问题描述
嗨!我对这段代码有一些问题,因为它可以在我的笔记本电脑(win 10)上运行,但是当我在旧计算机(win 7)上尝试它时,它每次都会崩溃。此外,有时,如果我有更多文件,它无法重新分配内存,但不仅如此(例如,它适用于 12 个文件,但在第 13 个文件上,它会崩溃)。所以现在这是修改后的代码,现在它在 win 7 上正常工作,但在 win 10 上不能正常工作,就像问题已经反转了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *f, *fc;
float lg, lt;
int q, l, i, n;
char lgs[20], lts[20], qs[5], *s, *t, *sir2="</parts></data>", *sir1="<?
xml version=\"1.0\"?><data><parts>";
char *ch, sl[100], numeI[20], numeO[20], *sir="text with 3 space pattern",
*sir3="some long text";
printf("INTRODU NUMARUL DE FISIERE: ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
if(i<10) sprintf(numeI, "0000000%d.###", i);
else sprintf(numeI, "000000%d.###", i);
f=fopen(numeI, "r");
if(f==NULL)
{
perror("Eroare deschidere fisier");
return(1);
}
sprintf(numeO, "optimizare%d.xml", i);
fc=fopen(numeO, "w");
if(fc==NULL)
{
perror("Eroare deschidere fisier");
return(1);
}
l=strlen(sir)+strlen(sir3);
s=(char*) malloc((strlen(sir1)+l+1));
strcpy(s, sir1);
fgets(sl, 100, f);
while(fgets(sl, 100, f))
{
strcat(s, sir);
sscanf(sl, "%f %f %d", &lg, <, &q);
lg=lg*10;
lt=lt*10;
sprintf(lgs, "%.2f", lg);
sprintf(lts, "%.2f", lt);
sprintf(qs, "%d", q);
ch=strstr(s, " ");
if(ch==NULL)
{
perror("EROARE CH 1");
}
strncpy(ch, lgs, strlen(lgs));
ch=strstr(s, " ");
if(ch==NULL)
{
perror("EROARE CH 2");
}
strncpy(ch, lts, strlen(lts));
ch=strstr(s, " ");
if(ch==NULL)
{
perror("EROARE CH 3");
}
strncpy(ch, qs, strlen(qs));
t=(char*) realloc(s, (strlen(s)+l+25));
if(t==NULL) {
perror("\nEROARE REALOCARE");
return 1;
}
s=t;
strcat(s, sir3);
}
t=(char*) realloc(s, (strlen(s)+strlen(sir2)));
if(t==NULL) {
perror("\nEROARE REALOCARE 2");
return 1;
}
s=t;
strcat(s, sir2);
fprintf(fc, s);
fclose(f);
fclose(fc);
}
printf("CONVERTIRE EFECTUATA");
} 你知道问题出在哪里吗?
解决方案
我很惊讶这适用于任何平台。
看看这两行:
ch=strstr(s, " ");
strncpy(ch, lgs, strlen(lgs));
" "
因此,您在字符串中搜索s
并且(不检查 NULL)只需将一些其他字符串复制到该位置。
但如果s
不包含该" "
模式,ch
将为 NULL 并且程序将在复制操作时崩溃。
那么是否s
包含模式?
我不这么认为!
s
第一次是如何建造的?
strcpy(s, sir1); // Copy of sir1
fgets(sl, 100, f);
while(fgets(sl, 100, f))
{
strcat(s, sir); // Append of sir
因为sir1
andsir
不包含该模式,所以也不会s
也ch
将是 NULL。
建议
始终检查返回值!
例子
ch = strstr(s, " ");
if (ch == NULL)
{
// Add error handling here
}
strncpy(ch, lgs, strlen(lgs));
这也适用于所有其他库调用(例如malloc
)
推荐阅读
- java - java.time.format.DateTimeFormatter.ISO_INSTANT 的格式字符串?
- rust - 一个人如何将一生限制在一个生锈的封闭环境中?
- pandas - 当我从一个 Excel 工作表复制数据并将其粘贴到另一个具有多个工作表的 Excel 文件时,其他工作表被删除
- javascript - 如何https请求?
- netsuite - 如何在库存明细子记录上设置序列号/批号的值?
- flutter - 如何在 Flutter 中获取 setState.of(context)?
- java - 为什么 NumberFormat 返回空白字段?
- python - UnboundLocalError:在 Pandas 中赋值之前引用了局部变量“y”
- javascript - 第一次点击反应后表格不呈现
- c++ - 使用函数而不是内联代码时 C++ 代码崩溃