Take the 2-minute tour ×

So I'm writing this code here and I simply want a function to return a character array and assign it to a variable in main function. Here is the function returning char*

char* getString(pid_t pid, long address, long length) 
    char* str =  (char *)malloc((length+1) * sizeof(char));
    int i =0;

    while (i < length)
        char t = ptrace(PTRACE_PEEKDATA,pid,address+i,0); 
        str[i] = t; 
    //  str[length] = '\0';
    printf(" Exiting getString %s \n ", str);
    return str;

And here is what I do in main

int main { 
    char* st = getString(pid, arguments[1], arguments[2]); // causes seg fault 
    // printf("getstring %s\n", getString(pid, arguments[1], arguments[2])); works fine
    // and produces correct output 
    return 1;

I haven't done much in C lately so maybe I'm missing something, but why does printf works and assigning fails? Can someone tell me what am I doing wrong here?

share|improve this question
add comment

1 Answer

You commented out the line in your function where you null terminate your string.

The fact that it only segfaults in one case in main() is simply luck (undefined behavior); you're calling printf() in your function as well.

share|improve this answer
oops. How did I not see it.. tnx for pointing it out! –  Rufat M Oct 22 '11 at 4:56
add comment

Your Answer


