讨教C语言 堆栈释放崩溃 问题

C语言 码拜 7年前 (2017-05-03) 1960次浏览
LZ最近刚开始自学C语言 学到堆栈内存部分的时候 遇到了很多奇奇怪怪的问题 很多问题LZ百思不得其解 希望各位大神不吝赐教。
关联问题1描述:释放堆内存的时候 本人感觉并没有越界操作的行为 但是每次程序执行到free的时候就会停 例如以下代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
typedef struct
{
	char name[16];
	unsigned char age;
	unsigned char sex;
} Student;
int main(void)
{
	Student *st = (Student *)malloc(sizeof(Student) * 2);
	memset(st, 0, sizeof(Student) * 2);
	for (int i = 0; i < 2; i++)
	{
		printf("pls input name:");
		scanf("%s", (st + i)->name);
		printf("pls input age:");
		scanf("%d", &(st + i)->age);
		printf("pls input sex(0/1):");
		scanf("%d", &(st + i)->sex);
		printf("\n");
	}
	free(st);
	return 0;
}

关联问题2描述:将以上代码中的st换成栈变量后 依然会报错 是在栈释放的时候出现ERROR提示 代码如下

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable:4996)
typedef struct
{
	char name[16];
	unsigned char age;
	unsigned char sex;
} Student;
int main(void)
{
	Student st[2] = { 0 };
	for (int i = 0; i < 2; i++)
	{
		printf("pls input name:");
		scanf("%s", st[i].name);
		printf("pls input age:");
		scanf("%d", &st[i].age);
		printf("pls input sex(0/1):");
		scanf("%d", &st[i].sex);
		printf("\n");
	}
	return 0;
}

错误截图如下讨教C语言 堆栈释放崩溃 问题
希望各位大神能指出以上代码中哪个部分出现了问题  有更加详细的解答当然更加好 小弟不胜感激

解决方案

80

对于第一个:
scanf(“%d”, &(st + i)->age); %d对应的应该是int,%c对应的是char,你的age要用%c
同理scanf(“%d”, &(st + i)->sex);这句

20

在每个最后不带\n的printf后面加fflush(stdout);
在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin);
另外请检查scanf的返回值。

//请今后要用
char c;
scanf("%c",&c);
//时,都改为
char s[2];
char c;
scanf("%1s",s);
c=s[0];

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明讨教C语言 堆栈释放崩溃 问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)