char* awesome_ini::aw_subStr(const char* line, size_t start, size_t length)
{
char subbuff[AWI_MAX_KEY_NAME_LENGTH];
memset(subbuff, 0, AWI_MAX_KEY_NAME_LENGTH);
size_t p = 0;
for (size_t i = start; i < length+1; i++)
{
subbuff[p] = line[i];
p++;
}
return (char*)subbuff;
}
char subbuff is stack allocated memory, you
NEVER return pointers to stack memory, this is because exactly what you are seeing is happening, instead you pass in a buffer that the function should write to(and you should pass in the size of that buffer).
The reason why you don't see this with objects is because when you return an object, you are copying the value from the function, so if i do:
struct Foo{
int x;
};
Foo Func(void){
Foo p;
p.x = 10;
return p;
}
int main(int argc, char **argv){
Foo f = Func();
printf("%d\n", f.x);
return 0;
}
what's happening is that when p is returned from func, the values of p are copied into the values of f, so your copying the values off the stack into another part of the stack that is still valid in the program context(note: this is a very simiplied explanation).
however if we do:
struct Foo{
int x;
};
Foo *Func(void){
Foo p[2];
p[0].x = 10;
p[1].x = 12;
return p;
}
int main(int argc, char **argv){
Foo *f = Func();
printf("%d\n", f[0].x);
return 0;
}
this is undefined behavior, and is very likely to crash the program, this is because you are returning a pointer into stack allocated memory that became invalid the moment you returned from Func. in many cases using the data immediately after would technically still work, but it is undefined and very bad to rely on such behavior.
one of the correct solutions is to do like so:
struct Foo{
int x;
};
bool Func(Foo *p, int psize){
if(psize<2) return false; //failed
p[0].x = 10;
p[1].x = 12;
return true; //succeded!
}
int main(int argc, char **argv){
Foo f[2];
Func(f, 2); // we can pass stack allocated memory into functions, we just should never return such memory!
printf("%d\n", f[0].x);
return 0;
}
edit:
I didn't think I would need a working example since I thought putting comments of the output would be enough.
always try to provide the minimalist working example to demonstrate your problem, you'll get more concise answers that way, then us trying to understand what the hell your doing.