Вопрос

I'm using a mysql snippet that connects to my mysql database (locally) in ANSI C. Everything is working perfectly, but I've been trying to create a function that connects to my database and inserts a new record based on some variables. I'm using sprintf to snag those variables and piece them together to form my SQL query.

Problem

Once I have my variables and my SQL ready, I send it over to mysql_query. Unfortunately, this does not work as expected, the program crashes and reports a buffer overflow.

Here are pieces of the overall function that may help explain the problem.

#include <mysql.h>
#include <string.h>
#include <stdio.h>

char *table = "test_table"; // table is called test_table
char *column = "value"; // column is called value
char *value = "working"; // what value we are inserting
char *query; // what we are sending to mysql_query

sprintf(query, "INSERT INTO %s (%s) VALUES ('%s')", table, column, value);

if (mysql_query(conn, query)) {
  fprintf(stderr, "%s\n", mysql_error(conn));
  return;
}

Purpose

The purpose of the overall function is so I don't have to keep rewriting SQL insert or update statements in my program. I want to call to one function and pass a few parameters that identify the table, columns and the values of said columns.

Any help would be most appreciated. I'm a bit rusty in C these days.

Question

Why is mysql_query not able to send the string?

Changes

This worked based on the comments.

const char *query[MAX_STRING_LENGTH];

sprintf((char *)query, "INSERT INTO %s (%s) VALUES ('%s')", table, column, value);

if (mysql_query(conn, (const char *)query)) {
Это было полезно?

Решение

You have no backing storage for query.

It's either set to NULL or some indeterminate value, depending on its storage duration, neither of which will end well :-)

Quick fix is to change it to

char query[1000];

though any coder worth their salary would also check to ensure buffer overflow didn't occur.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top