内存删除出现问题,在delete[] 处程序运行中断,希望大家能帮我看一下问题出在哪里。

图片说明

 #define _CRT_SECURE_NO_WARNINGS
#include <iostream> 
#include <iomanip> 
#include <math.h> 
#include <ctime> 
#include <thread>
#include <Windows.h>
using namespace std;

bool compare(const char *s, const char *q, int n)
{
    int i = 0;
    while (i<n)
    {
        if (q[i++] != s[i++])
            return false;
    }
    if (i = n && (s[n] - ' ' == 0 || s[n] - '\n' == 0 || s[n] == NULL))
        return true;
    else
        return false;
}

int Triangle_num(char* fname)
{
    FILE *fp;
    if ((fp = fopen(fname, "r ")) == NULL)
    {
        printf("Can't open file");
        exit(1);
    }

    int npoint = 0; //点个数
    int count = 0; //三角面片个数

    while (!feof(fp))     //feof()函数为判断文件是否结束,C语言
    {
        char f[256];
        fgets(f, 256, fp);
        if (compare(strtok(f, "   "), "vertex ", 6))
        {
            if (++npoint == 3)
            {
                count++;
                npoint = 0;
            }
        }
    }
    fclose(fp);
    return   count;
}

void main()
{
    char *a, *b;
    a = new char[50];
    b = new char[50];
    a = "C:\\Users\\Huan\\Desktop\\stl\\12workpiece.STL";
    b = a;
    Triangle_num(a);
    system("pause");    

    delete[] b;//增加delete之后出现报错
}
 char *a, *b;
    a = new char[50];
    b = new char[50];
    strcpy(a,"C:\\Users\\Huan\\Desktop\\stl\\12workpiece.STL");

    b = a;    // a 和 b 指向同一块区域
    //Triangle_num(a);
    //system("pause");  

    delete a;  释放其中之一就可以

用一段代码就知道问题在哪里了:

 #include <stdio.h>

int main(int argc, char **argv)
{
    char *a, *b;
    a = new char[50];
    b = new char[50];

    printf("a: %p b: %p\n", a, b);
    a = "C:\\Users\\Huan\\Desktop\\stl\\12workpiece.STL";
    b = a;
    printf("a: %p b: %p\n", a, b);

    return 0;
}

终端输出:
a: 0x80010288 b: 0x800102c0
a: 0x403070 b: 0x403070

new 了 a 和 b之后,这时 a地址是0x80010288 b地址是: 0x800102c0
执行了a = "C:\Users\Huan\Desktop\stl\12workpiece.STL";之后。a的地址又指向字符串所在的内存。
你delete的时候,将会去释放字符串的内存,而这个内存是不用去释放的。真正需要释放的new出来的内存却没有释放,所以还有内存泄露的问题。