将地址存储为来自char *的int *

时间:2016-12-13 16:10:36

标签: c arrays

我已经解析了objdump文件,并且在" out.txt"中只获得了如下的地址和函数名称。 file.Now我想将地址存储在const char **数组中的int *数组和函数名中,并使用了strtok,但是当我尝试使用atoi从char *转换为int *时,所有的字母都被删除了,那么我怎么能将函数名的地址存储在int * array?

400400 _init
400420 puts@plt-0x10
400430 puts@plt
400440 printf@plt
400450 __libc_start_main@plt
400460 .plt.got
400470 _start
400520 __do_global_dtors_aux
400540 frame_dummy
4005fd main
400660 __libc_csu_init
4006d0 __libc_csu_fini
4006d4 _fini



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

int main()
{

    FILE* fp;
    long file_size;
    char* buffer;

    fp = fopen("out.txt", "rb");
    if (!fp) {
        perror("out.txt");
        exit(1);
    }

    fseek(fp, 0L, SEEK_END);
    file_size = ftell(fp);
    rewind(fp);

    buffer = calloc(1, file_size + 1);
    if (!buffer) {
        fclose(fp);
        fputs("calloc failed", stderr);
        exit(1);
    }

    if (1 != fread(buffer, file_size, 1, fp)) {

        fclose(fp);
        free(buffer);
        fputs("can't read the file", stderr);
        exit(1);
    }

    printf("%s\n", buffer);

    int* address;
    const char** names;
    char* strArray[40];

    address = calloc(1, file_size + 1);
    names = calloc(1, file_size + 1);

    char* token = strtok(buffer, " \n");
    int i = 0;
    while (token) {
        printf("%2d %s\n", i, token);
        strArray[i] = strdup(token);
        token = strtok(NULL, " \n");    
        i++;
    }
    printf("i value is %d\n",i);
    int j=0;
    int count=0;

    while(j<i){
        address[count] = atoi(strArray[j]);
        names[count] = strArray[j + 1];
        count++;
        j = j + 2;
    }
    printf("Addresses:\n");
    for(int k=0;k<count;k++){
        printf("%d\n", address[k]);

    }

    printf("Function names:\n");
    for(int m=0;m<count;m++){

        printf("%s\n", names[m]);
    }

    return 0;
}

输出是这样的,当它将地址存储为int *时,它会删除所有字母

Addresses:
400400
400420
400430
400440
400450
4004
4004
400520
400540
4005
400660
4006
4006
Function names:
_init
puts@plt-0x10
puts@plt
printf@plt
__libc_start_main@plt
.plt.got
_start
__do_global_dtors_aux
frame_dummy
main
__libc_csu_init
__libc_csu_fini
_fini

1 个答案:

答案 0 :(得分:0)

atoi is for converting strings containing decimal numbers. You need to use strtoul with a base of 16 to convert strings containing hexadecimal addresses. You need to print them as hexadecimal numbers as well. – Ian Abbott