Question

I've been writing a program trying to find itself using the procps library. But for some reason it smashes the stack. This is my code:

int main(){
    PROCTAB *ptp;
    proc_t task;
    pid_t mypid[1];
    mypid[0] = getpid();
    printf("My id: %d\n", mypid[0]);
    ptp = openproc(PROC_PID, mypid, 1);
    if(readproc(ptp, &task)){
        printf("Task id:%d\n",task.XXXID);
    }
    else{
        printf("Error: could not find currect task\n");
    }
    closeproc(ptp);
    printf("Done\n");
    return 0;
}

The output i get when i run the program is:

$ ./test 
My id is: 8514
Task id is:8514
Done
*** stack smashing detected ***: ./test terminated
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(__fortify_fail+0x45)[0xb7688dd5]
/lib/i386-linux-gnu/libc.so.6(+0xffd8a)[0xb7688d8a]
./test[0x804863e]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0xb75a24d3]
./test[0x80484f1]
======= Memory map: ========
...
Aborted (core dumped)

Any one has an idea why it happens? Am I doing something wrong? Thanks.

Edit: I've looked at the header file and notice that I've made a wrong use of the openproc function the correct way to use it is (for pid) is to have the mypid array be null terminated, so I've change my code to:

int main(){
    PROCTAB *ptp;
    proc_t task;
    pid_t mypid[2];
    mypid[0] = getpid();
    memset(&mypid[1], 0, sizeof(pid_t));
    printf("My id: %d\n", mypid[0]);
    ptp = openproc(PROC_PID, mypid);
    if(readproc(ptp, &task)){
        printf("Task id:%d\n",task.XXXID);
    }
    else{
        printf("Error: could not find currect task\n");
    }
    closeproc(ptp);
    printf("Done\n");
    return 0;
}

and it still crushes the stack.

Was it helpful?

Solution

It works for me here. After getting that version of procps, it compiled and run fine:

$ gcc -Wall -Werror -o rp -L. -lproc-3.2.8 rp.c
$ ./rp
My id: 11468
Task id:11468
Done

Update

Try a modified version:

proc_t *result;
...
if((result = readproc(ptp, NULL))){
    printf("Task id:%d\n",result->XXXID);
    free(result);
}

OTHER TIPS

A possible cause for your crash is the fact that the proc_t struct returned by readproc() has additional dynamically allocated elements, such as environment variables or command line arguments. A safer way is to let readproc() allocate the whole structure, and free it later using freeproc():

while ((proc_info = readproc(proc, nullptr)) != NULL) {
    // do something with proc_info
    freeproc(proc_info);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top