Friday, March 20, 2009

My first C quiz at 2009

Hi dee Ho peeps!

It has been looong since I wrote last pitfall/quiz in here, so I guess it is about the time to continue :)

So at this time I'll just remind you of one nastyish C specific bug - which is easy to avoid by reading the compilers warnings. I've tested it on gcc.

So following code will work on 32 bit machine, but on 64 bit machine you are allowed to expect sudden death... What's the cause?

And as always, you can use comment section to give answers :)


file main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int data[32];
int i;
int *copydata;

for(i=0;i<32;i++)
{
data[i]=i;
printf("data[%d]=%d\n",i,data[i],i);
}


copydata=allocateMyMate(sizeof(data));
if(copydata==NULL)
{
printf("Allocation Failed!!\n");
return -1;
}
else
printf("Allocation succeeded!\n");

memcpy(copydata,data,32*sizeof(int));
printf("Looks like you had 32bit machine :) \n");
for(i=0;i<32;i++)
{
printf("data %d == copydata %d",data[i],copydata[i]);
}
return 0;
}




myalloc.c

#include <stdio.h>
#include <stdlib.h>

void * allocateMyMate(size_t size)
{
return malloc(size);
}




file main.c




So where's the bug?

And even though the free() corresponding to malloc() is missing, do not consider it as a bug at this time. (Naturally it is a bug, but it was not the bug I wrote this question for).

HINTS BELoW! Do Not Look YET ;)











1. With c++ youre safe from this bug.
2. Try compiling and check the compiler warnings!

2 comments:

  1. Current code showed here is not C but a broken copy pasted garbage.

    ReplyDelete
  2. True! I am terribly sorry, thanks for notifying me! This place is really not suitable for publishing code - < and > characters (at least) tend to break things apart!

    Anyways, I did some kind of fixed version about this code (I had lost the original). I did not check it for syntax errors, since I really had no time - but the idea should be present at least ;)

    ReplyDelete