Меню

Has triggered a breakpoint c ошибка

Zusul

1 / 1 / 1

Регистрация: 22.10.2012

Сообщений: 9

1

21.10.2013, 23:41. Показов 13999. Ответов 2

Метки нет (Все метки)


Парни C++ только начал изучать как пол года назад. Ссори если не правильно высказываюсь.
Делаю задачку. Не могу врубиться почему компилятор выдает ошибку app.exe has triggered a breakpoint. Компилятор Visual Studio 2013.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef HEAD_H_
#define HEAD_H_
 
#include<iostream>
 
class String
{
private:
    char * str;
    int len;
 
public:
    String(const char * s);
    String();
    String(const String & s);
    ~String();
    friend String operator+(const String & s1,const String & s2);
    friend std::ostream & operator<<(std::ostream & os, const String & s);
};
#endif
 
 
 
#include"Head.h"
#include<iostream>
#include<cstring>
 
String::String(const char * s)
{
    len = strlen(s);
    str = new char[len + 1];
    strcpy_s(str, len + 1, s);
}
String::String()
{
    str = new char[1];
    str[0] = '';
    len = 0;
}
String::String(const String & st)
{
    
    len = st.len;
    str = new char[len + 1]; 
    strcpy(str, st.str);
}
String::~String()
{
    
    delete [] str;
}
String  operator+(const String & s1, const String & s2)
{
    
    String s3;
    s3.len = strlen(s1.str) + strlen(s2.str);
    strncat_s(s3.str, s3.len + 1, s1.str, strlen(s1.str) );
    strncat_s(s3.str, s3.len + 1, s2.str, strlen(s2.str));
    return s3;
}
 
std::ostream & operator<<(std::ostream & os, const String & s)
{
    os << "The str = " << s.str << std::endl;
    return os;
}
 
#include"Head.h"
#include<iostream>
 
int main()
{
    String First = String("Vovan");
    String Second = String("Anus");
    String Third = String(First + Second);
    std::cout << Third;
    std::cin.get();
    return 0;
}

Заранее благодарен.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Убежденный

Ушел с форума

Эксперт С++

16454 / 7418 / 1186

Регистрация: 02.05.2013

Сообщений: 11,617

Записей в блоге: 1

21.10.2013, 23:56

2

Цитата
Сообщение от Zusul
Посмотреть сообщение

C++
1
2
3
4
5
6
7
8
String operator+(const String & s1, const String & s2)
{
String s3;
 s3.len = strlen(s1.str) + strlen(s2.str);
 strncat_s(s3.str, s3.len + 1, s1.str, strlen(s1.str) );
 strncat_s(s3.str, s3.len + 1, s2.str, strlen(s2.str));
 return s3;
}

Не вижу здесь выделения памяти под новую строку.

Кстати, у этого класса еще не хватает оператора присваивания.



1



Zusul

1 / 1 / 1

Регистрация: 22.10.2012

Сообщений: 9

22.10.2013, 13:58

 [ТС]

3

Спасибо большое разобрался!!!
Все теперь работает!

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#ifndef HEAD_H_
#define HEAD_H_
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
 
class String
{
private:
    char * str;
    int len;
 
public:
    String(const char * s);
    String();
    String(const String & s);
    ~String();
    String & operator=(const String &) ;
    friend String operator+(const String & s1,const String & s2);
    friend std::ostream & operator<<(std::ostream & os, const String & s);
};
#endif
 
#include"Head.h"
#include<iostream>
#include<cstring>
#define _CRT_SECURE_NO_WARNINGS
String::String(const char * s)
{
    len = strlen(s);
    str = new char[len + 1];
    strcpy_s(str, len + 1, s);
}
String::String()
{
    str = new char[1];
    str[0] = '';
    len = 0;
}
String::String(const String & st)
{
    
    len = st.len;
    str = new char[len + 1]; 
    strcpy(str, st.str);
}
String::~String()
{
    
    delete [] str;
}
String & String::operator=(const String & st)
{
    if (this == &st)
        return *this;
    delete []str;
    len = st.len;
    str = new char[len + 1];
    strcpy_s(str, len + 1, st.str);
    return *this;
}
String  operator+(const String & s1, const String & s2)
{
    
    String s3;
    s3.len = strlen(s1.str) + strlen(s2.str);
    s3.str = new char[s3.len + 1];
    strcpy_s(s3.str, s3.len + 1, s1.str); //strlen(s1.str) + 1);
    strncat_s(s3.str, s3.len + 1, s2.str, strlen(s2.str));// + 1);
    return s3;
}
 
std::ostream & operator<<(std::ostream & os, const String & s)
{
    os << "The str = " << s.str << std::endl;
    return os;
}
 
 
#include"Head.h"
#include<iostream>
 
int main()
{
    String First = String("Vovan");
    String Second = String("Vazilinchik");
    String Third;
    Third = First + Second;
    std::cout << Third;
    std::cin.get();
    return 0;
}



0



I’ve been always working on my software C++ & Java (build with Microsoft Visual Studio 2008 & Eclipse), and I’ve been trying to move it from a 32-bit system to a 64-bit one.

The compilation phase is alright, but on execution I get an error that says:

«Windows has triggered a breakpoint in javaw.exe. This may be due to
corruption of the heap, which indicates a bug in javaw.exe or any of
the DLLs it has loaded-.
This may also be due to user pressing F12 while javaw.exe has focus.
The output window may have more diagnostic information.
[BREAK] [CONTINUE] [IGNORE]»

You can see a snapshot of the error here:

enter image description here

Have you any idea of what this error means?
What does «corruption of the heap» mean?
Have you evere had any experience with this kind of error before?

Thank you so much!

asked Apr 16, 2012 at 10:29

DavideChicco.it's user avatar

DavideChicco.itDavideChicco.it

3,22013 gold badges52 silver badges84 bronze badges

1

It is a very nice feature of the Windows heap allocator, available since Vista. It tells you that your code has a pointer bug. Well, hopefully it is your code and not the JVM that has the bug 🙂 You’d better assume it is your code.

The actual cause ranges somewhere between mild, like trying to free memory that was already freed or allocated from another heap (not uncommon when you interop with another program), to drastically nasty, like having blown the heap to pieces earlier by overflowing a heap allocated buffer.

The diagnostic is not fine-grained enough to tell you exactly what went wrong, just that there’s something wrong. You typically chase it down with a careful code review and artificially disabling chunks of code until the error disappears. Such are the joys of explicit memory management. If the 32-bit version is clean (check it) then this can be associated with 64-bit code due to assumptions about pointer size. A 64-bit pointer doesn’t fit in an int or long, so it is going to get truncated. And using the truncated pointer value is going to trigger this assert. That’s the happy kind of problem, you’ll find the trouble code back in the Call Stack window.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges566 bronze badges

answered Apr 16, 2012 at 12:48

Hans Passant's user avatar

Hans PassantHans Passant

912k145 gold badges1670 silver badges2507 bronze badges

0

This unfortunately usually means a memory corruption. Some double freeing of memory, function that should return but doesn’t or any other type of undefined behavior.

Your best bet of solving this, unless you have a clue as to where this corruption is, is to use a memory analysis tool.

answered Apr 16, 2012 at 10:38

Luchian Grigore's user avatar

Luchian GrigoreLuchian Grigore

250k63 gold badges454 silver badges619 bronze badges

1

I got it!
Thanks to you all, I understood it was a problem of memory, and maybe of malloc()
In fact, I read here:

The bucket-sizing factor must be a multiple of 8 for 32-bit implementations and
a multiple of 16 for 64-bit implementations in order to guarantee that addresses
returned from malloc subsystem functions are properly aligned for all data types.

IBM.com:

So, I changed the malloc() sizing in the problem point. I went from:

(int**) malloc (const * sizeof(int))

to:

(int**) malloc (const * sizeof(int64_t))

And now it works!

Thanx a lot!

answered Apr 19, 2012 at 12:20

DavideChicco.it's user avatar

DavideChicco.itDavideChicco.it

3,22013 gold badges52 silver badges84 bronze badges

1

Typically that kind of errors occurs when you trying to access the memory you didn’t allocate. Check out all of your allocations (and freeing), especially pointer-to-pointer, and code that can access dinamically allocated memory. In your case size of poiners is 64bit insdead of 32bit, that should be prime cause.

answered Apr 16, 2012 at 10:41

tukaef's user avatar

2

  • Remove From My Forums
  • Question

  • Hello. I have the following problem. When my application is starting the following error occurs: «DelaunayWin32.exe has triggered a breakpoint». Where DelaunayWin32 is the name of my project. This error occurs on ShowWindow(hWnd,
    nCmdShow) function call. But this error does not always appear, but only from time to time, since often my application starts normally. If this error occurs and I click «Retry» button in the error message dialog then I can see the following
    picture:

    I apologize for the Russian-language comments in the source code of the application. Sometimes when I start my application, an error of a slightly different kind appears. Here it is.

    But again, I repeat, such things do not always happen. Sometimes, my application starts up normally. In Stackoverflow, MSDN, and other forums, I read several posts on this topic. But the discussions are so specific to each specific application that
    it is difficult to navigate them. If possible, please direct me in the right direction, that is, in what place of my application should I look for the cause of the error I’m talking about. Of course, I understand that this is not a simple thing,
    since, figuratively speaking, my application does not consist of ten lines of source code. Sometimes a similar error occurs when processing a WM_CLOSE message on a call to the DestroyWindow (hWnd) function. But again, I repeat, this does not always happen.
    Sometimes my application closes normally. If possible, please tell me what is the reason for this error. And from what place in the program I should start searching for the causes of this error. Thanks in advance.

    • Moved by

      Monday, June 29, 2020 1:37 AM

  • Home
  • Forum
  • General Programming Boards
  • C Programming
  • MSVS has triggered a breakpoint

  1. 04-06-2013


    #1

    generaltso78 is offline


    Registered User


    MSVS has triggered a breakpoint

    Hi guys,

    We are just learning how to implement calloc, malloc and free. At the end of my program, I keep getting a «windows has triggered a break point» error. Im pretty sure that this error is happening because of the way I am implementing free because this is the error I am getting in free.c — » retval = HeapFree(_crtheap, 0, pBlock);»

    here is the code which I allocate and free memory:

    Code:

    int main (){
         
        WORDS userWords[16];
        char **board;
        int i=0, n=0, numWords=0;
        srand(time(NULL));
          numWords = enterWords(userWords);
    
    
        board = (char **) calloc(20, sizeof(char));
        for (i=0; i<20; i++){
            board[i] = (char *) calloc(40, sizeof(char));
        }
        for(i=0; i<20; i++)
        {
            if(i != 0)
                printf("n");
            for(n=0; n<40; n++){
                board[i][n] = '0';
                printf("%c", board[i][n]);
            }
        }
        
        inputWords(userWords, board, numWords);
        cls;
        for(i=0; i<20; i++)
        {
            if(i != 0)
                printf("n");
            for(n=0; n<40; n++){
                printf("%c", board[i][n]);
            }
        }
        pause;
        populateGameBoard(userWords, board);
        displayGameBoard(userWords, board, numWords);
        pause;
        free(board);
        return 0;
    }


  2. 04-06-2013


    #2

    failure67 is offline


    Registered User


    We are just learning how to implement calloc, malloc and free. At the end of my program, I keep getting a «windows has triggered a break point» error. Im pretty sure that this error is happening because of the way I am implementing free because this is the error I am getting in free.c — » retval = HeapFree(_crtheap, 0, pBlock);»

    When people say they are implementing a function, they usually mean that they are writing that function. It doesn’t look like you are creating your own custom malloc, calloc, and free functions. I am assuming you meant that you are learning to use these functions rather than implementing custom versions of them.

    Code:

        board = (char **) calloc(20, sizeof(char));     
        for (i=0; i<20; i++){         
            board[i] = (char *) calloc(40, sizeof(char));     
        }

    You’re not allocating enough space for board. board is a pointer to a char pointer. sizeof (char) = 1. Unless you’re on some obscure system, sizeof (char *) will most likely be larger than that on your system.

    Try this:

    Code:

        board = calloc (20, sizeof (char *)) ;
        for (i=0; i<20; i++) {         
            board [i] = calloc (40, sizeof (char)) ;
        }

    I didn’t look at the rest of your code.

    Last edited by failure67; 04-06-2013 at 07:54 PM.


  3. 04-06-2013


    #3

    generaltso78 is offline


    Registered User


    I am getting «a value of type void* cannot be assigned to entity of type char**» with that calloc declaration. Is that because I declared char **board?

    Thanks


  4. 04-06-2013


    #4

    generaltso78 is offline


    Registered User


    Thanks Failure67,

    I got it to work with this:

    Code:

    board = (char **)calloc (20, sizeof (char* )) ;
    for (i=0; i<20; i++) {         
         board [i] = (char *)calloc (40, sizeof (char)) ;
    }

    I still don’t quite understand why. It looks like I am allocating 40 bytes to every value of i. Its not giving me the break error anymore though.


  5. 04-06-2013


    #5

    failure67 is offline


    Registered User


    I am getting «a value of type void* cannot be assigned to entity of type char**» with that calloc declaration. Is that because I declared char **board?

    My bad, I skipped the fact you’re using MSVS. MSVS is a c++ compiler, and the c++ language requires the casts that you added to your code. Pure C does not require (or recommend) those casts.

    I still don’t quite understand why. It looks like I am allocating 40 bytes to every value of i. Its not giving me the break error anymore though.

    The problem was specifically with this part:

    Code:

    board = (char **) calloc(20, sizeof(char));

    Because sizeof (char) < sizeof (char *), you have not allocated enough memory for 20 pointers. That’s why you had to change it to this:

    Code:

    board = (char **)calloc (20, sizeof (char* )) ;

    You also have a memory leak in your code. You have to free the 40 byte buffers that each of these 20 pointers pointed to.

    So you need to add something like this to the end of your code:

    Code:

    for (i = 0; i < 20; ++i) {
        free (board [i]) ; // Free the 40 byte buffers of each pointer
    }
    
    free (board) ; // Free the array of pointers


  6. 04-06-2013


    #6

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    Then you should name your source files to be prog.c, not prog.cpp.
    This should give the compiler driver the clue to use the C rather than C++ compiler.

    Or use this flag to force language choice.
    /Tc, /Tp, /TC, /TP (Specify Source File Type) (C++)


Popular pages

  • Exactly how to get started with C++ (or C) today
  • C Tutorial
  • C++ Tutorial
  • 5 ways you can learn to program faster
  • The 5 Most Common Problems New Programmers Face
  • How to set up a compiler
  • 8 Common programming Mistakes
  • What is C++11?
  • Creating a game, from start to finish

Recent additions subscribe to a feed

  • How to create a shared library on Linux with GCC — December 30, 2011
  • Enum classes and nullptr in C++11 — November 27, 2011
  • Learn about The Hash Table — November 20, 2011
  • Rvalue References and Move Semantics in C++11 — November 13, 2011
  • C and C++ for Java Programmers — November 5, 2011
  • A Gentle Introduction to C++ IO Streams — October 10, 2011

Similar Threads

  1. Replies: 2

    Last Post: 02-04-2011, 10:29 AM

  2. Replies: 3

    Last Post: 06-14-2010, 01:53 AM

  3. Replies: 2

    Last Post: 04-07-2009, 10:47 PM

  4. Replies: 0

    Last Post: 07-06-2008, 05:58 AM

  5. Replies: 2

    Last Post: 12-02-2005, 12:37 PM

Tags for this Thread

See more:

Hi all,

I want to extract all 3 grams(each 3 gram contain 3 byte with 1 byte shift each time) of files in a directory and count frequency of each 3 gram in files. I have written a simple C++ program to extract 3 grams of binary files recursively and saved them in a hash table as a key.
before I add each key I find key. if it was in heap I did not add this key and just increase member value(frequency of presence 3gram).

The program runs but it stops with an error message saying «windows has triggered a break point in my program.This may be due to the corruption of the heap which indicated a bug in the program or the dlls that it loads»

I would appreciate it if somebody could help me ..

Thanks,

#include "hash_table.h"
#include <string>
#include <windows.h>
#include <fstream>
#include <stdio.h>
#include <iostream>

#define MAX_BUFFER_SIZE 256
typedef CHashTable<int> CLongHashT;

using namespace std;

void makeVocabHash(string dir, CLongHashT HashTperAll, int N) {
	/* N -> N-gram! */
	HANDLE		  hFindFile;
	WIN32_FIND_DATAA  Win32FindData;
	CHAR	        Directory[MAX_PATH];
	int counter;
        int countNgram;
	int  i;
	string tmp;

	fstream fileOpen;

	// copying path to directory
	sprintf(Directory,"%s\*.*", &dir[0]);
      if((hFindFile = FindFirstFileA(Directory, &Win32FindData)) == INVALID_HANDLE_VALUE){ // if   directory not found (finding first file of directory)
		return ; // error, directory not found
	}

do{
if(strcmp(Win32FindData.cFileName, ".") != 0 && strcmp(Win32FindData.cFileName, "..") != 0){
sprintf(Directory, "%s\%s", &dir[0], Win32FindData.cFileName);


        // if found a file
        if(! (Win32FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
	// is a file
	fileOpen.open(Directory, ios::in | ios::binary | ios::ate);

	//size of file
	int end = fileOpen.tellg();
	fileOpen.seekg (0, ios::beg);
	int begin = fileOpen.tellg();
	int size = end - begin;
	char data[MAX_BUFFER_SIZE];

	fileOpen.read(&data[0], size);
	fileOpen.close();

	counter = 0;
	// reading data with N bytes, construct 3 grams and insert to hashT
    while(  (counter !=  ((size - N) + 1) ) ) {
	for( i=0; i!=N; ++i) 
		tmp += data[i+counter];

		// insert to hashT
		if (HashTperAll.GetMember(tmp))
		   countNgram = *(HashTperAll.GetMember(tmp)) + 1;
		else
		    countNgram = 1;
		
                HashTperAll.AddKey(tmp, &countNgram );
		tmp = "";
		counter++;
		}
			
	}
	else {
		// is a directory
		makeVocabHash(Directory, HashTperAll, N);
	}
		}
} while(FindNextFileA(hFindFile,&Win32FindData));//finding next file in directory

	// closing handles
	FindClose(hFindFile);
}
//---------------------------------------------------------------------
void main()
{
   CLongHashT HashTDocs;

   cout<< "enter a path";
   string dir;
   cin>> dir;
   makeVocabHash(dir,HashTDocs, 3);

}


1 solution

Solution 1

The problem may be located here:

char data[MAX_BUFFER_SIZE];

fileOpen.read(&data[0], size);

This results in a buffer overflow when your file size is greater than

MAX_BUFFER_SIZE<br />

.
To avoid this, allocate the buffer on the heap using new or malloc:

char data = new char[size];
fileOpen.read(&data[0], size);
// Do something with data here
delete data;

Comments

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

 

Print

Answers RSS

Top Experts
Last 24hrs This month

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

Windows is triggering a breakpoint in my program

Hi all,

I have written a simple C++ program to implement the string class. This class has member functions for +operator and =operator overload in addition to the constructors that I have defined for it.

The program runs but it stops with an error message saying «windows has triggered a break point in my program.This may be due to the corruption of the heap which indicated a bug in the program or the dlls that it loads»

The program produces correct output but it stops before returning the handle to the OS. I would appreciate it if somebody could help me ..

Thanks,
Puntis

Last edited on

You’ll have to post the code.

Following you could see my code:

//==============================================================

#pragma once
#include<iostream>
#include<cstring>
using std::cout;
using std::endl;

class MyCString{

private:

char* inputSTR;
size_t length;
size_t len1, len2, totalLength;

public:

MyCString(const char* STR=nullptr);
MyCString& operator=(const MyCString& mycstr);
void showSTR();
MyCString(const MyCString& mycstr1);
MyCString& operator+(const MyCString& mycstr);
~ MyCString();
};

//defining the constructor we define the sttring on the heap.
MyCString::MyCString(const char* STR):length(0), inputSTR(nullptr){

if (STR!=nullptr){
length = strlen(STR);
if (length>0){

inputSTR = new char[length+1];
strcpy_s(inputSTR, length+1, STR);
}
}
}//end of the constructor definition.

/*CSimpleString::CSimpleString(const CSimpleString& s)
{
len = s.len;
buff = new char[len+1];
strcpy_s(buff, len+1, s.buff);
}*/

//defining the copy constructor:
MyCString::MyCString(const MyCString& mycstr1){

inputSTR = new char[(mycstr1.length)+1];

strcpy_s(inputSTR,(mycstr1.length)+1, mycstr1.inputSTR);

}
//defining the assignment operator

MyCString& MyCString::operator= (const MyCString& mycstr){

//length = mycstr.length;

delete[] inputSTR;
inputSTR = new char (mycstr.length+1);

strcpy_s(inputSTR, (mycstr.length)+1, mycstr.inputSTR);

return *this;
}

MyCString& MyCString::operator+(const MyCString& mycstr){

//delete[] inputSTR;

//cout<<«this is:»<<this->inputSTR;
//cout<<«mycstr is:»<<mycstr.inputSTR;

len1 = this->length;
len2 = mycstr.length;
totalLength = len1+len2+2;
MyCString* concatedSTR;

concatedSTR->length = totalLength;
concatedSTR->inputSTR = new char[totalLength];
concatedSTR->inputSTR = strcat(this->inputSTR, mycstr.inputSTR);

// cout<<«test»<<concatedSTR.inputSTR ;
return *concatedSTR;
}

void MyCString::showSTR(){

cout<< «The string is: «<< inputSTR<<endl;

}

MyCString:: ~MyCString(){

delete[] inputSTR;

cout<<«Destructor is called.»<<endl;

}

//==================================================================

int main(){

MyCString st1= «test1»;
MyCString st2= «test2»;
MyCString st3=»»;
MyCString st5=»»;

st1.showSTR();

st3 = st1;

st3.showSTR();

MyCString st4(st2);
st4.showSTR();

st5 = st1 + st2;

st5.showSTR();

system(«PAUSE»);

return 0;
}

Last edited on

One problem is operator +. concatedSTR never points to anything. Though in fact, it shouldn’t be a pointer at all. If you allocated memory, you’d never delete it. Its fine to return by value.

I changed the return type of the operator+ function.So now it returns an object of the MyCString class type and no pointer. I figured out that the function perfectly runs as if I print out the concatedSTR in the function in has concatenated the two stings. But it never returns to the main program after and so it doesn’t run the next line in main program which is st5.showSTR();

Last edited on

A problem in operator =. You wrote () instead of []. Now only one char is allocated.
Also, you’re misusing strcat. It appends the 2nd string to the 1st one and the result is stored in 1st. You should first copy the 1st string with strcpy and then use strcat.

Thanks a lot Hamsterman. The problem is solved 🙂

Topic archived. No new replies allowed.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Hdd не проинициализирован ошибка ввода вывода
  • Harvia e9 ошибка ремонт