سؤال

This code causes a seg fault on my Ubuntu, Gentoo, Windows 7 64 bit(MinGW gcc very old version 3.6) but not on my friend's Windows 7 64 bit(MinGW gcc 4.6).

Here's the code(actually i can't understand how this can work on my friend's system, str is clearly not allocated).

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main() {
 char *str, *str1, *str2;

 printf(">>> ");
 scanf("%­s", str);

 for(str1 = str, str2 = strlen(str)+str-1; str2>str1; ++str1, --str2) {
   *str1 ^= *str2;
   *str2 ^= *str1;
   *str1 ^= *str2;
 }

 printf("<<< %­s", str);

 return 0;
}

Thank you in advance.

EDIT: He's just sent me his .exe, and actually works EVERY time, i launched it about 20 times. I have no words.

هل كانت مفيدة؟

المحلول 2

It may work on some system, sometimes, if you're lucky and the garbage value contained in the initialized pointer point to some valid memory. However, even if it doesn't crash, you write on some other process memory which may alter the way they work.

I had a funny experience once, I was working on a crypto routine but I messed the check to find the end of the buffer. The code encrypted memory until it crashed, and in the interval, it found the buffer where Windows stored the bitmap of the screen, I ended up with a nice artefact.

I guess such lucky context only happened on 32bits system, or if ASLR is disabled.

You're using MinGW and if I recall, it neither compiles in 64 bit by default, nor enable the use of ASLR, so if your friend had around 4 GB of RAM and his computer was running for some time, it can explains what you got. I guess the main difference between your Windows 7 and his are the quantity of RAM and the program you're running.

نصائح أخرى

This code invokes undefined behavior. Once UB is invoked then all bets are off. Anything could happen. The behavior may vary with compiler to compiler or even on different versions of same compiler you may get different results, either expected or unexpected, segmentation fault, program crash etc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top