c - Why does printing an uninitialized bool array as integers produce values besides 0 and 1? -


this question has answer here:

(also see mystery bool data type similar question relevant answers.)


while debugging program, noticed strange output when printing uninitialized bool array integers. consider c program:

#include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>  int main(void) {     int n = 30;     bool* bools = malloc(n * sizeof(bool)); // uninitialized memory.     (int i=0; i<n; ++i)     {         int x = bools[i];         assert(x == 0 || x == 1);         printf("%d ", x);     }     printf("\n");     free(bools); } 

due uninitialized bool array, output varies each run based on previous memory contents, of course. understanding casting bool int should produce either 0 or 1 (see assertion above, passes); however, see output this:

0 0 0 0 0 0 0 144 0 0 0 0 0 0 0 144 16 0 92 113 255 127 0 0 160 41 222 134 255 127 

can explain how program can print besides 0s , 1s?

update: short answer casting uninitialized bool int can produce values besides 0 , 1. (in case, bools stored bytes, uninitialized values can in [0..255].) also, assert line above seems optimized out, made problem more difficult debug.


to provide little more context: writing function count number of set bits in bool array, e.g.:

int popcount(const bool* v, int n) {     int c=0;     (int i=0; i<n; ++i) c += v[i];     return c; } 

i noticed return result greater n, seemed impossible. problem bool array uninitialized. zeroing array fixed problem, still doesn't make sense me how casting bool int produce besides 0 or 1.

because doesn't make sense restrict boolean read operations clamp actual value either 0 or 1.

the value of undefined variable can fits within variable's size. bool occupies single byte (because that's smallest addressable unit), , on systems 8-bit bytes means bool can store 256 different values. that's why numbers you're seeing range 0 255.

the implementation free assume not invoke ub, that's why you're seeing values besides 0 , 1. in code without ub, bools convert either 0 or 1.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -