Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain why this gets a seg fault (C programming)?

int load_byte(int memory[],int address) {
//This function works by finding the appropriate word then masking
//to obtain the relevant byte
int index,section;

    switch (address>>28) {
        case 0:
            index = address - START_ADDRESS;
            printf("index = %d",index);
        case 1:
            index = address - START_DATA_ADDRESS;
        case 7:
            index = address - START_STACK_ADDRESS;
   }

    section = index%4;
    index = index/4;
    switch (section) {
    case 0:
        return memory[index]&0x000000ff;
    case 1:
        return (memory[index]&0x0000ff00)>>8;
    case 2:
        return (memory[index]&0x00ff0000)>>16;
    case 3:
        return (memory[index]&0xff000000)>>24;
    }

}

START_ADDRESS has a value of 0x00400000 and the sample address I used was 0x00400002, it's just this function that keeps giving me a seg fault, don't quite understand why as the array in question has a size of 1000. Thanks in advance.

like image 267
user1776600 Avatar asked Oct 26 '12 09:10

user1776600


2 Answers

Your first switch looks strange, only 0, 1 and 7 are handled. And there are no break; statements at the end of each case.

like image 84
Werner Henze Avatar answered Oct 19 '22 20:10

Werner Henze


The code:

switch (address>>28) {
    case 0:
        index = address - START_ADDRESS;
        printf("index = %d",index);
    case 1:
        index = address - START_DATA_ADDRESS;
    case 7:
        index = address - START_STACK_ADDRESS;
    }

Since the address is 0x00400002, so the switch will start execution from case 0, and you don't have any break in each case X, all the code will be run. That is, at last the index will equal to address - START_STACK_ADDRESS.

Maybe this was the reason.

Try to add breaks between cases.

switch (address>>28) {
    case 0:
        index = address - START_ADDRESS;
        printf("index = %d",index);
        break;
    case 1:
        index = address - START_DATA_ADDRESS;
        break;
    case 7:
        index = address - START_STACK_ADDRESS;
}
like image 1
Marcus Avatar answered Oct 19 '22 21:10

Marcus