-1

MAIN.C triggers function 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);


}

function b() in MAIN.H responds with result

static inline const char *b(){

const char* retu;
char query[300];

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

retu = query;

    return retu;
}

this is what MAIN.C script prints:

v����

it is strange stuff. not as expected. ( intended )

2 Answers2

3

retu is pointing to query, which goes out of scope when b is finished, so the memory is no longer valid in main.

To make a string that outlasts b, you need to allocate it on the heap, e.g. using malloc.

happydave
  • 7,127
  • 1
  • 26
  • 25
0
const char* retu;
char query[300];
sprintf(query, "select * from TEST limit 1");
retu = query;
return retu;
}  //query goes out of scope here

As soon as the function ends query goes out of scope since it is declared on stack.Now you are trying to refer this memory after it has gone out of scope which is undefined behavior.You can allocate query on heap.Also remember to free the memory.

 char *query = malloc(sizeof(char) * 300);  
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34