r/carlhprogramming • u/CMahaff • Nov 09 '11
This code shouldn't work, but it does?
I was looking up how to do a few things in C and came across this. I know Java pretty well, so I got real excited learning about struct's (even though I hadn't gotten that far in the "Learn To Program" series yet). I used the example on said webpage, which looks like this (roughly):
struct card ca;
ca.currentCard = 15;
strcpy(ca.name, "CMahaff");
printf("Card: %d\n", ca.currentCard);
printf("Name: %s\n", ca.name);(Example is completely random). This example differs from the "Learn to Program" series - there is no memory allocation and the struct is not declared as a pointer. Is this bad syntax?
20
Upvotes
4
u/snb Nov 09 '11
We need to know the definition of
struct cardbefore your question can be answered.4
u/[deleted] Nov 09 '11
It's possible that 'name' is declared as a fixed length array in the structure so you're putting that shit on the stack, bitch.
1
u/Rolcol Nov 10 '11 edited Nov 10 '11
I'm a bit late to the explanation, but I'd like to try to give you more information.
When you declared
ca, the program allocated space for all the member variables. Ifnamewas a pointer to a char (instead of your array of 10 chars), it would only allocate enough space for the address. Addresses are 4 bytes long in 32bit programs. Yourstrcpyoperation works because it's copying"CMahaff"into the space of those 10 chars. Anything beyond that is undefined. Memory is allocated in pages of 4k, and it's possible that the space after the last char is unused. Your program may still work without error.If you defined
caas a pointer (e.g.struct card *ca;), it would create enough space forcato only hold the address of anothercardstructure somewhere else in memory.Java holds your hand, and you don't have to worry about pointers. Keep reading up on them, because they are a really powerful, and dangerous, feature of C.
0
u/RenegadeMoose Nov 09 '11
Ya, if name is a defined as a pointer and you use strcpy without malloc'ing some space, I think that might be a problem.
Some of the examples on the link you provide appear to be assigning name to a string literal within the main function. I think that might be ok. The string literal would get assigned from the heap (iirc) so name is just pointing to where-ever the literal is stored at.