I'm using a DOS virtual machine to bypass a segfault, yet Turbo-C doesn't want to compile this code:
#include <stdio.h>
int main() {
FILE *fp = fopen("somefile.txt", "w");
if(fp == NULL) {
fprintf(stderr, "NaF");
return -1;
}
char /*1*/ *ch = NULL;
while(ch /*2*/ < (char *) 209* /*3*/1024) {
fprintf(fp, "& - %p, * - %c\n", ch, *ch/*4*/);
ch++;
}
fclose(fp);
return 0;
}
Error list:
I assume this must be some kind of ancient C, because I'm positive this code would compile on a modern compiler. I am aware it would produce a segfault, hence why I'm writing in a DOS environment.
1) and 2) Turbo-C used the C90 version of the standard. It did not allow variable declarations in the middle of a { }
body, but only at the top. Therefore char* ch
has to be moved:
int main (void)
{
char* ch = NULL
...
3) You try to multiply a pointer (char *) 209
. This simply isn't allowed in C and will not compile on modern compilers either.
And finally, pointer arithmetic ch++
used on a pointer which doesn't point at an allocated object isn't well-defined by any version of C. It probably worked in Turbo C, but no guarantees.
I think this program was supposed to grab a memory dump of RAM and store it to a text file. MS DOS allowed direct access of memory. However, the code was already questionable even back in 1989.
Using char
for accessing raw memory is a bad idea, since it is a type with implementation-defined signedness. Use unsigned char
or uint8_t
instead.