How does Visual Studio decide the order in which stack variables should be allocated?

Posted by Jason on Stack Overflow See other posts from Stack Overflow or by Jason
Published on 2010-05-05T00:24:37Z Indexed on 2010/05/05 0:28 UTC
Read the original article Hit count: 575

I'm trying to turn some of the programs in gera's Insecure Programming by example into client/server applications that could be used in capture the flag scenarios to teach exploit development. The problem I'm having is that I'm not sure how Visual Studio (I'm using 2005 Professional Edition) decides where to allocate variables on the stack.

When I compile and run example 1:

int main() {
    int cookie;
    char buf[80];

    printf("buf: %08x cookie: %08x\n", &buf, &cookie);
    gets(buf);

    if (cookie == 0x41424344)
        printf("you win!\n");
}

I get the following result:

buf: 0012ff14 cookie: 0012ff64

buf starts at an address eighty bytes lower than cookie, and any four bytes that are copied in buf after the first eighty will appear in cookie.

The problem I'm having is when I place this code in some other function. When I compile and run the following code, I get a different result: buf appears at an address greater than cookie's.

void ClientSocketHandler(SOCKET cs){
 int cookie;
 char buf[80];
 char stringToSend[160];
 int numBytesRecved;
 int totalNumBytes;

 sprintf(stringToSend,"buf: %08x cookie: %08x\n",&buf,&cookie);
 send(cs,stringToSend,strlen(stringToSend),NULL);

The result is:

buf: 0012fd00 cookie: 0012fcfc

Now there is no way to set cookie to arbitrary data via overwriting buf. Is there any way to tell Visual Studio to allocate cookie before buf? Is there any way to tell beforehand how the variables will be allocated?

Thanks,

Jason

© Stack Overflow or respective owner

Related posts about visual-studio

Related posts about stackoverflow