简体   繁体   中英

store the address as int* from char*

I have parsed objdump file and got only the addresses and function names as follows in "out.txt" file.Now I want to store addresses in int* array and function names in const char** array and have used strtok, but when I am trying convert from char* to int* using atoi all the alphabets are deleted, so how can I store the addresses of the function names in 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;
}

The output is like this, it's deleting all the alphabets when it's storing the address as 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM