简体   繁体   中英

Why these char arrays seem to be out of bounds? (Linux System Programming example / C / readv)

This example is taken from the Linux System Programming book, page 88.

Code: http://pastebin.com/mEfmHbPP

The referenced text file 'buccaneer.txt' has such contents:


The term buccaneer comes from the word boucan.
A boucan is a wooden frame used for cooking meat.
Buccaneer is the West Indies name for a pirate.

The output of this program should be 3 such lines:


0: The term buccaneer comes from the word boucan.
1: A boucan is a wooden frame used for cooking meat.
2: Buccaneer is the West Indies name for a pirate.

But something strange happens on my machine and such output is displayed:


0: The term buccaneer comes from the word boucan.
1: A boucan is a wooden frame used for cooking meat.
Buccaneer is the West Indies name for a pirate.
The term buccaneer comes from the word boucan.
2: Buccaneer is the West Indies name for a pirate.
The term buccaneer comes from the word boucan.

when testing this I see that arrays foo , bar and baz report proper sizeof() values, the iovcnt equals 3 and the nr value returned by readv is 145 which is consistent with the file size reported by my system. When I try to print contents of each array, the still report correct sizeof() BUT the contain WAY more characters. From the last listing: 1st line - contents of foo, lines 2,3,4 - contents of bar, lines 5,6 - contents of baz.

I'm not new to C but I haven't run into such problem yet. Please advise.

There is no null terminator on each string - so, sizeof will be OK, but your variables themselves will not be. Either add a null terminator to each string or use the following formatting string for your printf:

"%x.xs"

(replace X with the sizeof value for the string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM