String Acts Unexpectedly

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdio>

struct A {
	const char *name;

	void setName (const char *n) {
		name = n;
	}
};

void Assign (A *a) {
	char string[256] = "test";      // <------------

	a->setName(string);
}
int main () {
	
	A *a;
	a = new A();

	Assign(a);

	printf("%s", a->name);

	return 0;
}


Currently, running this code will output nothing.

If I change the line signified by "<---------" to
 
char *string = "test";

or
 
const char *string = "test";

it outputs "test".

If I change the line to
 
char string[] = "test";

or
 
char string[5] = "test";

it outputs junk.

If I don't use declare "a" as a pointer, and instead as an object (passing its address in to Assign()), it outputs "test".
If I copy the code inside the Assign() function and paste it where I call Assign(), it outputs "test".

I think I might sort of have a feeling of what is happening, but I wouldn't be able to explain it if I tried.

Could someone tell me what the problem is? Don't tell me how to fix it (unless you know a different way that might be useful), because I obviously already know how to fix it. I just want to know what is going on.

Just so you know, the project I ran into this problem on is making it hard to fix this. I need to be able to change each character individually in "string" before passing it into "a". That can't be done with "char *" (I think?), so I need to use "char [256]", but I ran into this.
Well, the different way I'd suggest would be using a std::string.

Anyways, if you can't/ don't want to do that:
1: Don't assign C strings to each other..
Use strcpy or strncpy instead.
2: Arrays and pointers are not the same thing:
http://www.lysator.liu.se/c/c-faq/c-2.html
Last edited on
Thanks, hanst99.

I think I completely get what is going on now. The pointer is pointing to a string (and is, itself, not a string, as you proved to me with that link). So when I reach the end of the "Assign" function, "string" gets butt raped by the garbage collector, but now "a" holds a pointer to it. That's why it comes out as junk. And when I copied and pasted the code in "Assign" to where I call "Assign", it worked because "string" hadn't been butt raped yet. I was also able to fix the problem in my project too, using this knowledge.

Thanks!
There is no real GC in C++, but you're close enough. Glad it works for you now.
Topic archived. No new replies allowed.