Задача: Напишите функцию, которая добавляет рядом с пробелом еще один (случае где два и больше подряд пробелов не учитываем). Функция должна принимать в качестве аргументов строку (массив символов). Функция должна возвращать новую сформированную строку.
В общем программа работает , но, в конце вот такая табличка:
КОД:
#include "pch.h"
#include <iostream>
#include <Windows.h>
void add_spaces(char* a)
{
int count = 0;
for (int i = 0; i < strlen(a); i++)
{
if (a[i] == ' ')
count++;
}
char* new_arr = new char[strlen(a) + count];
for (int i = 0, j = 0; i < strlen(new_arr); i++, j++)
{
if (a[j] == ' ')
{
new_arr[i] = ' ';
new_arr[i + 1] = ' ';
i++;
}
new_arr[i] = a[j];
}
for (int i = 0; i < strlen(new_arr); i++)
{
std::cout << new_arr[i];
}
delete[]new_arr;
}
int main()
{
using namespace std;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
char a[] = " ";
cout << "Введите строку: ";
cin.getline(a, 128);
cout << "nСтрока после добавления пробелов: ";
add_spaces(a);
}
- Remove From My Forums
Microsoft Visual C++ Debug Error — when exception thrown
-
Question
-
My Visual Studio 2008 is defying the laws as I know them. The debugger is exiting an application, between a try and catch block, and popping up a dialog that says, «Microsoft Visual C++ Debug Library — Debug Error! This application
has requested the Runtime to terminate it in an unusual way. Please contact the application’s support team for more information.This occurs right as a _com_error is thrown. The exception is thrown within a try, which is immediatly followed by a catch(_com_error & e) block. The catch never gets hit. Instead this dialog pops up. If I click rety, I am taken to some internal exit
code and the call stack does not contain any of my code. I double checked the thread IDs and they match at a breakpoint on the throw and where the debugger takes me when I hit retry. So, it is the same thread.I have no idea what is causing this.
What causes an error dialog to pop up with a this message as opposed to an unhandled exception?
Answers
-
I think I may have found the source of my problems. It seems the original author of the code I am working on had no regard for releasing COM interfaces, releasing COM itself, or freeing any resources at all before letting an exception make its way across
boundries. I’ll know for sure after a whole lot of editing.-
Marked as answer by
Thursday, April 21, 2011 3:52 PM
-
Marked as answer by
You can use ASSERT
or _ASSERT
macro for assert-and-debug. Or, you can craft your own assert-macro. Use the definition of _ASSERT
(taken from crtdbg.h
):
#define _ASSERT_EXPR(expr, msg)
(void) ((!!(expr)) ||
(1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, NULL, L"%s", msg)) ||
(_CrtDbgBreak(), 0))
The important function here is _CrtDbgReportW, which will display the assertion dialog-box having three standard buttons (Abort, Retry and Ignore). Depending on return value you can then call other functions. In the macro given above, function _CrtDbgBreak
is called when user hits ‘Retry’ button (which causes function to return 1, see MSDN).
You may write to a log file, display to debug output window (using OutputDebugString
), or do things you may like.
A bug is a mistake or error in a program that causes it not to work correctly. Debugging is the process of removing and fixing bugs to get a program to function properly. There are different types of bugs that have different causes and solutions. Bugs can be errors, mistakes, oversights, or poorly implemented logic. Some bugs are easy to detect and fix while others are difficult to recognize and rectify. A bug will ultimately cause a compile error, a runtime error, or an incorrect result.
Compile Errors
Compile Errors occur at compile-time when a language rule has been broken. A program will not run if it has an error in compilation. To detect compile errors use Debug → Compile VBAProject on the toolbar in the Visual Basic Editor. Using Debug → Compile will compile the code in all modules and raise an error message if there is a compile error anywhere, whereas running a procedure in one module may not show the compile error in another procedure or module.
Syntax Errors are compile errors that occur because a syntax rule has been broken. Syntax is the structure of a language and determines what is considered a valid statement. By default, Auto Syntax Check is enabled and the Visual Basic Editor will alert syntax errors and certain other compile errors and highlight them red. If auto syntax check is disabled, pop-up messages will not appear but syntax errors will still appear in red. To enable or disable auto syntax check go to Tools → Options → Editor → Code Settings → Auto syntax check.
Unhandled Runtime Errors
Runtime Errors occur while a program is running. Unhandled runtime errors will cause program execution to pause and a message will be displayed. The user can either press End to end execution of the program or press Debug to open the Visual Basic Editor and view the line of code that caused the runtime error. Runtime errors can be handled using the On Error statement which is discussed in the Error Handling section.
Logical Errors
Bugs which cause incorrect output can be the trickiest to debug because the code can appear to work properly under the right conditions but then work incorrectly under other conditions. These silent logical errors are usually caused by poorly thought-out or poorly implemented logic or overlooking aspects of a problem or solution. This type of bug can often be caught through testing and reviewing the output of the code.
Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long
'BAD CODE - If MinValue > MaxValue erroneous results occur
Randomize
RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)
End Function
Public Function RandomLong(MinValue As Long, MaxValue As Long) As Long
'FIXED - Unacceptable state causes a runtime error instead of returning wrong answers
If MinValue > MaxValue Then
Err.Raise 5
End If
Randomize
RandomLong = Int((MaxValue - MinValue + 1) * Rnd + MinValue)
End Function
A runtime error could exist within a silent error if it only occurs under specific conditions. Code may run normally under normal conditions but then break when an edge case is encountered, causing an unhandled runtime error which can leave a program or associated data in an intermediate state.
Debug Object
The Debug object contains two methods which assist in debugging VBA code, Print and Assert. The Debug object has a default global instance and cannot be instantiated. The Debug object can be accessed at any time in VBA just by typing Debug.
Debug.Print
Debug.Print is used to print text to the Immediate Window.
Public Sub Example()
Debug.Print "Hello, World!"
End Sub
Debug.Assert
Debug.Assert will pause execution if a boolean expression does not evaluate to True. If the expression evaluates to False or Null execution will be paused.
Public Sub Example()
Debug.Assert 1 > 0
Debug.Assert True
Debug.Assert 1
Debug.Assert 1 < 0 'Pauses Execution
Debug.Assert False 'Pauses Execution
Debug.Assert 0 'Pauses Execution
Debug.Assert Null 'Pauses Execution
End Sub
Pause Program Execution
There are a number of ways to cause a program to pause execution and allow the user to inspect the state of a program in break mode.
Breakpoints
Breakpoints can be used in the Visual Basic Editor to pause program execution when a particular line of code is reached. Execution will pause before the line of code is executed. Breakpoints can be toggled by clicking in the margin next to the line of code, right-clicking the line of code and selecting Toggle → Breakpoint, or by using the Edit or Debug toolbars.
Stop Statement
The Stop statement will pause execution when the keyword is encountered in the code.
Watches
Watches can be used to pause execution when an expression evaluates to True or when the value of an expression changes.
Runtime Errors
By default, when an unhandled runtime error is encountered a message will appear describing the error, giving the option to End program execution or to Debug. Selecting Debug will jump to the line of code that caused the error and leave program execution paused.
Different error trapping options can be selected to pause execution on all errors or to pause on errors inside class modules.
Error Trapping Option | Description |
---|---|
Break on All Errors | Will enter break mode when any error is encountered regardless of error handling code. |
Break in Class Module | Will enter break mode and show error inside class modules. |
Break on Unhandled Errors | This is the default setting. Will enter break mode when an unhandled runtime error occurs. |
Debug.Assert
Debug.Assert will cause execution to pause if a boolean expression does not evaluate to True. If the expression evaluates to False or Null execution will pause.
Public Sub Example()
Debug.Assert 1 = 0
Debug.Assert False
Debug.Assert 0
Debug.Assert Null
End Sub
Stepping Through Code
There are tools in the Visual Basic Editor for stepping through code which allow developers to take a close look at the way a program executes each line of code. There is: Step Into, Step Over, Step Out, and Run To Cursor. These tools can be accessed from the Debug Toolbar or by using keyboard shortcuts.
Tool | Shortcut | Description |
---|---|---|
Step Into | F8 | Executes a line of code and enters into procedures. |
Step Over | Shift + F8 | Executes a line of code but will not enter procedures. |
Step Out | Ctrl + Shift + F8 | Executes all lines of code within a procedure. |
Run to Cursor | Ctrl + F8 | Executes all lines of code up to where the cursor is currently located. |
Navigating Code
Navigating code is an important skill for programming as well as debugging. When a project grows it becomes more complicated to navigate the code. The Visual Basic Editor provides tools that facilitate navigating code.
Definition Shortcut
The Definition shortcut allows the developer to jump directly to a where a variable or procedure is defined. To jump to the definition of a variable or procedure right-click on the identifier and select Definition from the right-click menu or use the keyboard shortcut Shift + F2.
LastPosition Shortcut
The LastPosition shortcut allows the developer to jump to the position in code they last edited. To jump to the last position right-click in the Visual Basic Editor and select LastPosition or use the keyboard shortcut Ctrl + Shift + F2.
Bookmarks
Bookmarks can be used to explicitly set positions in the code that can be cycled through. To set a Bookmark right-click on the line of code and select Toggle → Bookmark. To cycle through Bookmarks, use the Edit Toolbar.
Object Box and Procedure Box
The object box and procedure box drop-downs allow a developer to view all the objects and procedures in a module and jump directly to specific procedures as well as insert event procedures if applicable. The object box and procedure box are located at the top of the coding window. The object box is on the left and the procedure box is on the right.
Split Code Window
The code window can be split so different parts of the same code window can be viewed simultaneously. To split the code window drag the handle at the top right corner of the code window.
Split code windows view the same code and changes in either window are reflected in both windows.
Module And Procedure View
Code windows can be toggled between module view and procedure view. Module view makes the entire module visible in the code window. Procedure view makes only the current procedure visible in the code window. To toggle between module view and procedure view use the toggle buttons at the bottom left corner of the code window.
Useful Shortcuts
Action | Shortcut | Description |
---|---|---|
Intellisense | Ctrl + j | Shows options for completing code |
Auto-Completion | Ctrl + space | Completes code or shows options for completing code |
Definition | Shift + F2 | Jumps to where a variable or procedure is defined |
Last Position | Ctrl + Shift + F2 | Jumps to the last active position in a code module |
Important Windows
The Immediate Window, Locals Window, and Watch Window are all powerful debugging tools. These windows can be accessed from the View menu in the Visual Basic Editor.
Immediate Window
The Immediate Window can be used to view output, run code, and evaluate expressions. The Immediate Window can be accessed by pressing Ctrl + g in the Visual Basic Editor or from View → Immediate Window.
Debug.Print
Debug.Print outputs text to the immediate window. For example, Debug.Print «Hello, World!» will output «Hello, World!» to the immediate window.
Call Procedures
Procedures can be called from the immediate window by typing the name of the procedure followed by any parameters and pressing enter.
Evaluate Expressions Using «?»
To evaluate an expression in the immediate window type a «?» followed by the expression and press enter.
Execute Code Statements
Code can be typed directly in the immediate window and executed. Because only one line can be used in the immediate window to type code, write multiple statement using the «:» statement separator.
Locals Window
The Locals windows is used to track the values and types of variables during program execution. Pausing execution, stepping through code, and looking at the locals window is an effective way to observe changes in the state of a program. The Locals Window can be accessed from View → Locals Window.
Watches
The Watch Window is used to view how expressions evaluate during a program’s execution and to pause execution when certain conditions are reached. To Add a watch, highlight an expression, right-click the expression, and select Add Watch. Alternatively, right-click the Watch Window, select Add Watch, and type the expression. To access the Watch Window navigate to View → Watch Window.
Call Stack Window
The call stack window shows a list of active procedures. To see the call stack dialog either navigate to View → Call Stack, click the call stack icon on the Debug toolbar, or use the shortcut Ctrl + L.
Debugging Error
Hi there again! I have been learning c++ using addison wesley programming principles and practices using c++ 2nd edition. Below is a code i came up real quick using this particular library. However, when I run the code and enter my input as something that is not «5», I get a debug error and abort () has been called. It should read the line within the error function, and I don’t understand why it isn’t doing so.
|
|
However, when I run the code and enter my input as something that is not «5», I get a debug error and abort () has been called.
Yes, that’s because you haven’t defined your exception handlers. Try this (I’m not going to because I don’t have Stroustrup’s predefined header std_lib_facilities.h on hand):
|
|
EDIT: And if anyone else is reading this and doesn’t understand/didn’t read Stroustrup’s book, he advises everyone to utilize a precompiled header he created specifically for the book PPP, which #includes most of the libraries needed to run the code in the book, defines namespace std, and also has a simple error handler.
Last edited on
Now it works great, thanks! If it isn’t too much trouble, would you mind explaining exception handlers and the try/catch function you used? I really appreciate the help!
Edit: Thanks «Yawzheek» I just read your edited post. Thanks for the advice!
Last edited on
Ya know, I would love to, but Stroustrup does a FAR better job than I ever could in chapter 5, and I’ll just give you half advice. If I could summarize it, I would say:
Basically what you’re doing is setting up simplified error handling that will give you a better message than the garbled nonsense you’ll usually get when you encounter run-time errors. The try aspect is just «defining» scope to look for them (I guess you would say?) and catch is just where errors are «caught» to give you a meaningful message to output. For example:
|
|
The first function is what your error(«MESSAGE») goes to if you supply it. Your message should be something that identifies where the problem was found and/or what it was, and it’s passed along. The second function is, as the output suggests, when an exception was caught, but it’s not well known.
|
|
To be honest, I don’t even like telling you that much because I don’t know for certain the specifics, but that’s what I know from using it, and I don’t want to lead you down the wrong path. The other problem is that Stroustrup personalized it heavily for the text, so (as far as I am on chapter 19) I can’t say for certain if he breaks it down further. Sorry
Also, you may find it useful (or possibly not), but I like to include __func__ (those are 2 ‘_’ characters) to include the name of the function the error was found inside.
Last edited on
Gotya, this gives me a good fundamental idea of exception handlers. Thanks alot, I really appreciate it! I’ll definitely check the chapter and section out when i get to it.
Topic archived. No new replies allowed.