69,373
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdbool.h>
#include<string.h>
#include<stdlib.h>
#define LENGTH 5
#define str_len 20
char str1[] = "quirt";
int main()
{
double *pS = (double*)calloc(LENGTH, sizeof(double));
double *psTemp = NULL;
char str[str_len] = "\0";
size_t temp = LENGTH;
double number[LENGTH] = { 0.0 };
bool flag = true;
size_t n = 0;
printf_s("Enter your numbers input \"quirt\" end:\n");
while (flag)
{
for (int i = 0; i < LENGTH; i++)
{
printf_s("%zd enter :", n + 1);
scanf_s("%s", str, str_len);
if (!strcmp(str, str1))
{
flag = false;
break;
}
if (n + 1 > temp)
{
for (int i = 0; i < n;i++)
printf_s("&pS=%p\n", pS+i);
if (!(psTemp = (double*)realloc(pS, LENGTH + n)))
{
printf_s("Error memory realloc.\n");
return 1;
}
pS = psTemp;
temp = temp + LENGTH;
for (int i = 0; i < LENGTH + n; i++)
printf_s("&pS=%p\n", pS + i);
printf_s("The memory crea extend to %zd\n", LENGTH+n);
for (int i = 0; i < LENGTH+n; i++)
printf_s("------%.3lf\n", *(pS + i));
}
*(pS + n) = atof(str);
n++;
}
}
long double count = 0.0;
printf_s("n=%zd\n", n);
for (int i = 0; i < n; i++)
{
count = count + *(pS + i);
printf_s("pS[%d]=%.3lf ", i, *(pS + i));
if ((i + 1) % 5 == 0)
printf_s("\n");
}
printf_s("\nThe total is %.3lf.\nThe avg is:%.3lf.\n", count, count / n);
psTemp = NULL;
printf_s("11111\n");
free(pS);
printf_s("11111\n");
pS = NULL;
printf_s("11111\n");
return 0;
}
#include <time.h>
#include <stdlib.h>
#include <windows.h>
int main() {
int a,b[11];//本来是b[10],为判断哪句越界,故意声明为b[11]
srand((unsigned int)time(NULL));//按两次F11,等黄色右箭头指向本行时,调试、新建断点、新建数据断点,地址:&b[10],字节计数:4,确定。
while (1) {//按F5,会停在下面某句,此时a的值为10,b[10]已经被修改为对应0..4之一。
b[(a=rand()%11)]=0;
Sleep(100);
b[(a=rand()%11)]=1;
Sleep(100);
b[(a=rand()%11)]=2;
Sleep(100);
b[(a=rand()%11)]=3;
Sleep(100);
b[(a=rand()%11)]=4;
Sleep(100);
}
return 0;
}
char *p=malloc(500);
memset(p,7,1000);
free(p);
[quote=引用 2楼小灸舞 的回复:]你这个肯定是越界破坏了堆空间。 导致内存管理信息被破坏,所以free出错
检查使用分配的内存有没出现越界情况,如果有会破坏了堆空间,通常表现在释放的时候出错