Page 1 of 1

C: malloc() vs varName[arraySize]

Posted: Mon Oct 20, 2003 9:22 pm
by nigma
Hey, do any of the C programmers who hang out here know why you would use malloc() to allocate memory instead of just doing like

Code: Select all

char blahї20];
Thanks for any help / advice provided.

Posted: Tue Oct 21, 2003 7:21 am
by volka
the stack is fix-sized when the program runs. You can't do something like

Code: Select all

size_t tLen = strlen(szSomething);
char blahїtLen+1];
strcpy(blah, szSomething);
but you can do

Code: Select all

size_t tLen = strlen(szSomething);
char* blah = (char*)malloc(tLen+1);
strcpy(blah, szSomething);
same with lists, you don't know (or might not know) how much data is to store.

Posted: Tue Oct 21, 2003 7:55 am
by nigma
Alright, thanks volka. When then would you use the brackets to provide the size of an array?

Posted: Tue Oct 21, 2003 8:57 am
by volka
when either I or the compiler exactly know how much data there is (at maximum).

Code: Select all

char threeLetterAcronymї3];
Point triangleї] = { {0, 1}, {1, 0}, {2, 1} };
char itoaBufї21]; // int64 might use up to 20 characters on radix=10
	
_itoa( i, itoaBuf, 10);
stack overflows are a serious threat to security. Many bugs and exploits are the result of not handling the stack correctly

Posted: Tue Oct 21, 2003 10:47 am
by nigma
Thanks a bunch volka, very understandable explanation. Apreciate the help.