danielmhanover danielmhanover - 1 year ago 114
C Question

C Mysterious Overflow

Why does this code output -32768 and not 32768? Looks like an overflow but I cannot figure out where.

#include <stdio.h>
#include <stdlib.h>
int main()
char *buffer = (char*)malloc(sizeof(char)*2);
buffer[0] = 0x80;
buffer[1] = 0x00;
int address = (buffer[0]<<8) | (buffer[1]);
printf("%d\n", address); //outputs -32768
return 0;

Answer Source

On your compiler char is signed.

On your compiler, 0x80 is converted to -0x80 to fit in a signed char.

So buffer[0] holds -128, and ((-128)<<8) | (0) evaluates to -32768.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download