C: malloc() vs varName[arraySize]

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

C: malloc() vs varName[arraySize]

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post by nigma »

Alright, thanks volka. When then would you use the brackets to provide the size of an array?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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
User avatar
nigma
DevNet Resident
Posts: 1094
Joined: Sat Jan 25, 2003 1:49 am

Post by nigma »

Thanks a bunch volka, very understandable explanation. Apreciate the help.
Post Reply