读书人

一个既超级简单又超级复杂的C语言有关

发布时间: 2012-11-08 08:48:11 作者: rapoo

一个既超级简单又超级复杂的C语言问题:
程序一:
#include<stdio.h>
#include<stdlib.h>

int main()
{
char *s;
int nLen = 100;

// malloc申请的空间最多存储长度为100的字符串
// 最后一个字节存储字符串结尾符
s = (char *)malloc((nLen + 1) * sizeof(char));

gets(s);
puts(s);

free(s);
s = NULL;

return 0;
}
能够运行!
程序二:
#include<stdio.h>
#include<stdlib.h>

int main()
{
char *s;

s = (char *)malloc(sizeof(char));

gets(s);
puts(s);

free(s);
s = NULL;

return 0;
}
不能运行!

程序三:
#include<stdio.h>
#include<stdlib.h>

int main()
{
char *s;
s = (char *)malloc( sizeof(char));
gets(s);
puts(s);
return 0;
}
可以运行!

程序四:
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="djksafd";
char *str=s;
char s1[2];
strcpy(s1,str);
printf("%s\n",s1);
return 0;
}
不能运行!

程序五:
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="djksafd";
char *str="hakdshkdsak";
char s1[2];
strcpy(s1,str);
printf("%s\n",s1);
return 0;
}
可以运行!

程序六:
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="djksafd";
char *str=s;
char s1[20];
strcpy(s1,str);
printf("%s\n",str);
return 0;
}
可以运行!

程序七:
程序一:
#include<stdio.h>
#include<stdlib.h>

int main()
{
char *s;
int nLen = 100;

// malloc申请的空间最多存储长度为100的字符串
// 最后一个字节存储字符串结尾符
s = (char *)malloc((nLen + 1) * sizeof(char));

gets(s);
puts(s);

free(s);
s = NULL;

return 0;
}
能够运行!
程序二:
#include<stdio.h>
#include<stdlib.h>

int main()
{
char *s;

s = (char *)malloc(sizeof(char));

gets(s);
puts(s);

free(s);
s = NULL;

return 0;
}
不能运行!

程序三:
#include<stdio.h>
#include<stdlib.h>

int main()
{
char *s;
s = (char *)malloc( sizeof(char));
gets(s);
puts(s);
return 0;
}
可以运行!

程序四:
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="djksafd";
char *str=s;
char s1[2];
strcpy(s1,str);
printf("%s\n",s1);
return 0;
}
不能运行!

程序五:
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="djksafd";
char *str="hakdshkdsak";
char s1[2];
strcpy(s1,str);
printf("%s\n",s1);
return 0;
}
可以运行!

程序六:
#include<stdio.h>
#include<string.h>
int main()
{
char s[20]="djksafd";
char *str=s;
char s1[2];
strcpy(s1,str);
printf("%s\n",str);
return 0;
}

不能运行!

这是怎么回事?请专家解答!

[解决办法]
不管你相不相信, 程序二真的可以运行, 只是你malloc时, 未加错误处理, 所以可能会运行出错, 而且, 只分配了一个单元的空间, 而你有用的是gets()获得数据, 很容易溢出, 但并不是一定会溢出, 这与你系统对内存页的定义和运行程序时内存的剩余量有关。一次的运行结果并不是普遍规律! 程序4与以上分析的相似, 有时可以运行, 有时不能运行, 这是因为这个程序本身存在bug(s), 因为本身会溢出, 而运行成功只能说明是小概率事件发生了。


这个问题的关键在于, 程序会溢出。

读书人网 >C语言

热点推荐