功能打印奇怪的字符:v����

时间:2017-06-11 02:11:15

标签: c

MAIN.C 触发功能 b()

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mysql.h>
#include "main.h"

int main() {


const char *a;
a = b();

printf("%s\n", a);


}
MAIN.H 中的功能 b()以结果回复

static inline const char *b(){

const char* retu;
char query[300];

sprintf(query, "select * from TEST limit 1");

retu = query;

    return retu;
}

这是 MAIN.C 脚本打印的内容:

v����
这是奇怪的事情。不像预期的那样。 (打算)

2 个答案:

答案 0 :(得分:3)

retu指向query,当b结束时超出范围,因此内存在main中不再有效。

要创建一个比b更长的字符串,您需要在堆上分配它,例如使用malloc。

答案 1 :(得分:0)

function synchronousCode(pool, school, meal){
    var conn = pool.getConnection().data;
    var sql = "SELECT * FROM daily WHERE school = ? AND meal = ?";
    var rows = conn.query(sql, [school,meal]).data;
    // rows from 'daily' table are ready at this point
    var qMarks = "";
    var foodNames = [school];
    for(var i=0; i<rows.length; i++) {
        foodNames.push(rows[i].name);
        qMarks += "?,";
    };
    qMarks = qMarks.substring(0, qMarks.length - 1);
    sql = "SELECT * FROM foods WHERE school = ? AND name IN (" + qMarks + ")";
    var foods = conn.query(sql, foodNames).data;
    // rows from 'foods' table are ready at this point
    ... process food, or ...
    return foods;
};

var nsynjs = require('nsynjs');
var school =..., meal = ..., pool = ...;
nsynjs.run(synchronousCode,{},pool, school, meal,function(foods){
    console.log('synchronousCodeis done',foods);
});

一旦函数结束const char* retu; char query[300]; sprintf(query, "select * from TEST limit 1"); retu = query; return retu; } //query goes out of scope here 超出范围,因为它在stack上声明。现在你试图在它超出范围之后引用这个内存,这是未定义的行为。你可以分配{{在堆上。还记得释放内存。

query