Why does my program run on Ubuntu gcc but not OSX gcc?
So my homework, I ran it in Ubuntu, and it compiles fine and runs like the way it should. But when I run this in Mac OSX, it gets a bus error. Why is that?
I'm compiling with gcc -m32 source.c -o test
Here's the Mac OSX version (added prefixed underscores):
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char phrase[] = "slow but sure";
int sz;
int ph开发者_如何学Crasesz;
char *arg;
char *result;
// Add any extra variables you may need here.
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Usage: %s takes 1 string argument.\n", argv[0]);
exit(1);
}
// Allocate memory and copy argument string into arg.
sz = strlen(argv[1]) + 1;
arg = malloc(sz);
strcpy(arg, argv[1]);
// Allocate lots of memory for the result.
phrasesz = strlen(phrase) + 1;
result = malloc(sz * phrasesz);
// Now copy phrase into result, while replacing SPACE
// with SPACE+arg+SPACE.
__asm__("\n\
leal _phrase, %esi\n\
movl _result, %ebx\n\
outerLoop:\n\
cmpb $0, (%esi)\n\
je finished\n\
forLoop:\n\
cmpb $32,(%esi)\n\
je endLoop\n\
cmpb $0, (%esi)\n\
je finished\n\
mov (%esi), %eax\n\
mov %eax, (%ebx)\n\
incl %ebx\n\
incl %esi\n\
jmp forLoop\n\
endLoop:\n\
mov (%esi), %eax\n\
mov %eax, (%ebx)\n\
incl %ebx\n\
incl %esi\n\
movl _arg, %edx\n\
copyArgv1IntoResult:\n\
cmpb $0, (%edx)\n\
je finishedCopyingArgv1\n\
mov (%edx), %ecx\n\
mov %ecx, (%ebx)\n\
incl %ebx\n\
incl %edx\n\
jmp copyArgv1IntoResult\n\
finishedCopyingArgv1:\n\
movb $32, (%ebx)\n\
incl %ebx\n\
jmp outerLoop\n\
finished:\n\
movb $0, (%ebx)\n\
");
printf("%s\n", result);
return 0;
}
Update:
I ran it in gdb debugger and this is the error I am getting.
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION_FAILURE at address: 0x00000000
0x00001ee8 in finished ()
1: x/i $pc 0x1ee8 <finished+11>: mov (%eax),%eax
Also, I am removing the Ubuntu version so there's less scrolling.
Some of your instructions, like...
mov (%esi), %eax
...are copying more than a byte from the character buffer at a time. I assume that's accidental? You'd do well to write the code in C then use gcc -S and compare to your hand-written code. Even if the buffers are aligned to a word-boundary, you're incrementing the pointers by one byte, so certain to attempt an unaligned memory read. A sigbus basically means that you're trying to read a word's worth of memory from an address that points to a byte that's not at the start of an aligned word, but some CPUs silently if slowly battle on while others bail out. I've no idea of the hardware differences between your hosts.
精彩评论