Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this C programming reading?

Tags:

c

file-io

This is the code I am trying to understand:

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main(void){

    unsigned long word;
    ssize_t nr;

    int file = open("koray.txt",O_RDONLY);

    nr = read(file,&word,sizeof(unsigned long));
    printf("%li\n",word);

}

koray.txt has only 1 character that is k.

When I run the program I see:

koray@koray-VirtualBox:~$ ./a.out
4195435

What is this large value?

like image 544
Koray Tugay Avatar asked Jan 08 '23 07:01

Koray Tugay


1 Answers

There will be random garbage in the word variable because you never initialized it. Then read will only be able to get one byte from the file (nr probably returned 1, you should check that!) which saves one byte, but the word variable still has 3-7 bytes of uninitialized junk in it that gets printed.

like image 130
Adam D. Ruppe Avatar answered Jan 13 '23 18:01

Adam D. Ruppe