Sunday 15 May 2011

malloc zero bytes for unsigned int in C -



malloc zero bytes for unsigned int in C -

#include<stdio.h> #include<stdlib.h> void main(){ unsigned int *p, a[25]; unsigned char *s = "goodcoffee"; unsigned int size, size1, size2, test_variable; size1 = sizeof(unsigned int); size2 = sizeof(unsigned int *); size = sizeof(unsigned int)/sizeof(unsigned int *); p = malloc(sizeof(unsigned int)/sizeof(unsigned int*)); test_variable = 0xffffffff; *p = 0xffffffff; strcpy(a,s); printf("size of int: %d , size of int *: %d, size: %d, test variable: %d\n",size1,size2,size,test_variable); printf("%s %d \n", a, *p); return; }

hi, trying understand why below mentioned behavior seen. need help understand happens code. here malloc allocating 0 bytes. (this interview question).

output:

size of int: 4, size of int *: 4, size:1 , test_variable: -1 goodcoffee -1

i not understand why test_variable showing -1 though unsigned int. happens lastly nibble. tried giving range of value 0 f lastly nibble. code giving different negative values. if rid of lastly nibble, i.e.test_variable 0xfffffff, output 268435455.

here malloc allocating 0 bytes.

malloc not allocating 0 bytes, allocating 1 bytes machine.. as

size = sizeof(unsigned int)/sizeof(unsigned int*) //gives 1

so, p pointing 1 byte

and

*p = 0xffffffff;

you trying store 4 byte number in p while p pointing @ 1 byte allocated space. undefined behaviour.

c

No comments:

Post a Comment