Я работаю над сценарием Python для сбора и вставки данных на удаленный сервер Postgres, и я случайно начал получать эту ошибку даже для сценария, который работал раньше.
Python(42869,0x1ff51bac0) malloc: double free for ptr 0x12d939800 Python(42869,0x1ff51bac0) malloc: *** set a breakpoint in malloc_error_break to debug
вот мой файл базы данных
import psycopg2 as pg
import json
# function to make a query by specifying the database name
import config
def get_db_conn():
"""
Connects to the specified database and returns the connection object.
Parameters:
dbname (str): The name of the database to connect to.
Returns:
psycopg2.extensions.connection: The connection object.
Raises:
psycopg2.Error: If there is an error connecting to the database.
"""
conn = pg.connect(
host=config.DB_HOST ,
port=config.DB_PORT,
user=config.DB_USER,
password=config.DB_PASS,
database=config.DB_NAME)
return conn
def db_operations(query, isread=True, return_data=False):
"""
Perform database operations based on the provided query.
Args:
database (str): The name of the database to connect to.
query (str): The SQL query to execute.
isread (bool, optional): Specifies whether the query is a read operation or not. Defaults to True.
return_data (bool, optional): Specifies whether to return the data fetched from the query. Defaults to False.
Returns:
tuple: A tuple containing a boolean value indicating the success of the operation and the result of the operation.
If the operation is successful, the first element of the tuple is True. Otherwise, it is False.
If the operation is a read operation and return_data is True, the second element of the tuple is a JSON string
containing the fetched data. If return_data is False, the second element of the tuple is 'OK'.
If the operation is not a read operation, the second element of the tuple is 'OK' if the operation is successful,
otherwise it contains the error message.
"""
conn = get_db_conn()
cursor = conn.cursor()
try:
cursor.execute(query)
if isread:
data = [dict(zip([column[0] for column in cursor.description], row)) for row in cursor.fetchall()]
return True, json.dumps(data)
else:
conn.commit()
if return_data:
data = [dict(zip([column[0] for column in cursor.description], row)) for row in cursor.fetchall()]
return True, json.dumps(data)
return True, 'OK'
except (Exception) as error:
conn.rollback()
conn.commit()
print("Error while connecting to PostgreSQL:", error)
return False, error
finally:
cursor.close()
conn.close()
Я использую MacBook Air m2, Python версии 3.9.6 (даже пробовал с 3.11.6 и 3.12.3), psycopg2 версии 2.9.9 и Postgres версии 14.11.
Я пытался вставить данные на свой удаленный сервер postgresql, но получил двойную бесплатную ошибку malloc.
@TimRoberts Справедливый комментарий, но, конечно же, базовая реализация не должна допускать такой ошибки на уровне C.
@Тим Робертс, спасибо, что указал на это. Я тоже это отметил и обновил
Вы установили psycopg2 или psycopg2-binary?
Вероятно, это связано с этой ошибкой в psql, которая исправлена в последних версиях.
Например, из примечаний к выпуску 13.14:
Исправление несовместимости с OpenSSL 3.2 (Тристан Партин, Бо Андресон)
Используйте поле «app_data» BIO для нашего частного хранилища вместо того, чтобы предполагать, что можно использовать поле «data». Раньше эта ошибка не вызывала проблем, но в 3.2 она приводит к вылетам и жалобам на двойное освобождение.
В Homebrew есть проблема , для которой есть несколько предлагаемых обходных путей, основной из которых — обновление до последней версии обслуживания, или, надеюсь, к настоящему времени они уже получили патч.
Вы должны закончить ЛИБО
rollback
илиcommit
. Эти двое являются противоположностями друг друга. И ваша внутренняя частьcommit
не должна находиться внутри предложенияtry
, которое может делать другиеrollback
иcommit
.