Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Python Help with Stack Buffer Overflow

JimmysNetwork

Legendary Coder
Hi all,

I am working on a new project, and I can't seem to get past an issue with getting an error code;
[Done] exited with code=3221226505 in 5.251 seconds

My understanding is;

The exit code 3221226505 corresponds to a stack buffer overrun (also known as a stack buffer overflow), which is a type of memory corruption issue. It indicates that your program attempted to use more stack memory than allocated, potentially overwriting memory that should not have been modified, leading to a crash.

I may be overlooking the issue, as I have been working onthe entire project for hours now. I would appreciate it if anyone here has an idea as to what is causing the software to crash.

Python:
import logging
from PyQt5.QtWidgets import (
    QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout,
    QTableWidget, QTableWidgetItem, QComboBox, QMessageBox, QSizePolicy,
    QSpacerItem
)
from PyQt5.QtCore import Qt
from db import get_connection
from datetime import datetime

# Set up logging to log errors
logging.basicConfig(level=logging.ERROR, filename="app.log", filemode="a", format="%(asctime)s - %(levelname)s - %(message)s")

class PurchaseOrderWindow(QWidget):
    def __init__(self, user_id, stack=None):
        super().__init__()
        self.setWindowTitle("Create Purchase Order")
        self.setGeometry(200, 200, 800, 600)
        self.user_id = user_id
        self.stack = stack
        self.items_data = {}
        self.deleted_rows = []

        self.load_inventory_items()

        layout = QVBoxLayout()
        if self.stack:
            layout.setMenuBar(create_main_menu(self, self.stack, self.user_id))

        layout.addSpacerItem(QSpacerItem(20, 30, QSizePolicy.Minimum, QSizePolicy.Expanding))

        layout.addWidget(QLabel("PO Number"))
        self.po_number_input = QLineEdit()
        self.set_next_po_number()
        layout.addWidget(self.po_number_input)

        layout.addWidget(QLabel("Client"))
        self.client_dropdown = QComboBox()
        self.load_clients()
        layout.addWidget(self.client_dropdown)

        self.date_label = QLabel(f"Date: {datetime.now().strftime('%Y-%m-%d')}")
        self.date_label.setAlignment(Qt.AlignRight)
        self.date_label.setStyleSheet("font-style: italic; color: gray;")
        layout.addWidget(self.date_label)

        layout.addWidget(QLabel("PO Items"))
        self.table = QTableWidget()
        self.table.setColumnCount(4)
        self.table.setHorizontalHeaderLabels(["Item Name", "Quantity", "Unit Price", "Total"])
        self.table.setDragDropMode(QTableWidget.InternalMove)
        self.table.setFocusPolicy(Qt.StrongFocus)
        self.table.keyPressEvent = self.handle_table_keypress
        layout.addWidget(self.table)

        # Dropdown for PO Status (Draft, Open, Confirmed, Completed)
        self.status_label = QLabel("PO Status")
        self.status_dropdown = QComboBox()
        self.status_dropdown.addItems(["Draft", "Open", "Confirmed", "Completed"])
        layout.addWidget(self.status_label)
        layout.addWidget(self.status_dropdown)

        self.total_label = QLabel("Total: $0.00")
        self.total_label.setAlignment(Qt.AlignRight)
        self.total_label.setStyleSheet("font-size: 14px; font-weight: bold;")
        layout.addWidget(self.total_label)

        buttons_layout = QHBoxLayout()
        self.add_row_button = QPushButton("Add Item Row")
        self.add_row_button.clicked.connect(self.add_item_row)
        self.remove_row_button = QPushButton("Remove Selected Row")
        self.remove_row_button.clicked.connect(self.remove_selected_row)
        self.undo_button = QPushButton("Undo Delete")
        self.undo_button.clicked.connect(self.undo_delete)
        self.save_po_button = QPushButton("Save Purchase Order")
        self.save_po_button.clicked.connect(self.save_po)

        buttons_layout.addWidget(self.add_row_button)
        buttons_layout.addWidget(self.remove_row_button)
        buttons_layout.addWidget(self.undo_button)
        buttons_layout.addWidget(self.save_po_button)
        layout.addLayout(buttons_layout)

        layout.addSpacerItem(QSpacerItem(20, 30, QSizePolicy.Minimum, QSizePolicy.Expanding))

        self.setLayout(layout)

    def load_inventory_items(self):
        try:
            conn = get_connection()
            cursor = conn.cursor()
            cursor.execute("SELECT name, quantity, unit_price FROM items")
            for name, qty, price in cursor.fetchall():
                self.items_data[name] = {"quantity": qty, "unit_price": float(price)}
            cursor.close()
            conn.close()
        except Exception as e:
            logging.error(f"Failed to load inventory items: {e}")
            QMessageBox.critical(self, "Error", "Could not load inventory items.")

    def load_clients(self):
        try:
            conn = get_connection()
            cursor = conn.cursor()
            cursor.execute("SELECT id, name FROM clients ORDER BY name")
            for client_id, name in cursor.fetchall():
                self.client_dropdown.addItem(name, client_id)
            cursor.close()
            conn.close()
        except Exception as e:
            logging.error(f"Failed to load clients: {e}")
            QMessageBox.critical(self, "Error", "Could not load clients.")

    def set_next_po_number(self):
        try:
            conn = get_connection()
            cursor = conn.cursor()
            cursor.execute("SELECT MAX(CAST(SUBSTRING(po_number, 4) AS UNSIGNED)) FROM purchase_orders")
            result = cursor.fetchone()
            next_number = (result[0] or 0) + 1
            self.po_number_input.setText(f"PO-{next_number:04d}")
            cursor.close()
            conn.close()
        except Exception as e:
            logging.error(f"Error generating PO number: {e}")
            print("Error generating PO number:", e)

    def save_po(self):
        po_number = self.po_number_input.text()
        client_id = self.client_dropdown.currentIndex()
        status = self.status_dropdown.currentText().lower()

        # Debugging print
        logging.debug(f"PO Number: {po_number}, Client ID: {client_id}, Status: {status}")

        if not po_number or client_id == -1:  # Check for invalid client selection
            QMessageBox.warning(self, "Error", "PO number and client selection are required.")
            return

        items = []
        for row in range(self.table.rowCount()):
            combo = self.table.cellWidget(row, 0)
            qty_input = self.table.cellWidget(row, 1)
            price_item = self.table.item(row, 2)
            if not combo or not qty_input or not price_item:
                continue
            name = combo.currentText()
            try:
                qty = int(qty_input.text())
                price = float(price_item.text())
            except ValueError:
                continue
            if qty <= 0:
                continue
            items.append((name, qty, price))

        if not items:
            QMessageBox.warning(self, "Error", "At least one valid item is required.")
            return

        try:
            conn = get_connection()
            cursor = conn.cursor()

            cursor.execute("SELECT id FROM purchase_orders WHERE po_number = %s", (po_number,))
            if cursor.fetchone():
                QMessageBox.warning(self, "Error", "PO number already exists. Please choose a different one.")
                return

            logging.debug(f"Inserting PO with status: {status}")

            cursor.execute("INSERT INTO purchase_orders (po_number, client_id, created_by, status) VALUES (%s, %s, %s, %s)",
                           (po_number, client_id, self.user_id, status))
            po_id = cursor.lastrowid

            logging.debug(f"Inserted PO with ID: {po_id}")

            for name, qty, price in items:
                cursor.execute(
                    "INSERT INTO po_items (po_id, item_name, quantity, unit_price) VALUES (%s, %s, %s, %s)",
                    (po_id, name, qty, price)
                )
                cursor.execute(
                    "UPDATE items SET quantity = quantity - %s WHERE name = %s",
                    (qty, name)
                )

            conn.commit()
            QMessageBox.information(self, "Success", "Purchase Order saved!")
            if self.stack:
                self.stack.addWidget(POListWindow(stack=self.stack))
                self.stack.setCurrentIndex(self.stack.count() - 1)
            else:
                self.close()

        except Exception as e:
            logging.error(f"Failed to save PO: {e}")
            QMessageBox.critical(self, "Error", f"Failed to save PO: {e}")
            conn.rollback()

        finally:
            cursor.close()
            conn.close()

Thanks in advance!
 
Last edited:
Solution
I ended up figuring out the issues:

Summary of Fixes:​

ProblemFix
cellWidget() on empty cellsCall add_item_row() at startup
Missing widgets in tableAdded QComboBox, QLineEdit, etc. properly
Unsafe event overrideRemoved self.table.keyPressEvent = ...
Missing importsAdded create_main_menu and POListWindow
I ended up figuring out the issues:

Summary of Fixes:​

ProblemFix
cellWidget() on empty cellsCall add_item_row() at startup
Missing widgets in tableAdded QComboBox, QLineEdit, etc. properly
Unsafe event overrideRemoved self.table.keyPressEvent = ...
Missing importsAdded create_main_menu and POListWindow
 
Solution

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom