Pointers, Arrays, Strings, and Malloc in C

I am currently studying strings, pointers and arrays in C. I tried to write a program in which an array contains three pointers to string addresses. Everything seems to work, but the program behaves strangely.

Here is the code:

char** getUserDetails() { char* host = "localhost"; char* username = "root"; char* password = "mypassword"; // create array for holding pointers to strings char *userDetailsHolder[3]; userDetailsHolder[0] = malloc(sizeof(char)*strlen(host)); strcpy(userDetailsHolder[0], host); userDetailsHolder[1] = malloc(sizeof(char)*strlen(username)); strcpy(userDetailsHolder[1], username); userDetailsHolder[2] = malloc(sizeof(char)*strlen(password)); strcpy(userDetailsHolder[2], password); return userDetailsHolder; } int main() { char** userDetails = getUserDetails(); printf("Host: %s\nUsername: %s\nPassword: %s\n", userDetails[0], userDetails[1], userDetails[2]); printf("Host: %s\nUsername: %s\nPassword: %s\n", userDetails[0], userDetails[1], userDetails[2]); return 0; } 

Exit: output indicates that something went horribly wrong

 Host: localhost Username: root Password: mypassword Host: root Username: localhost Password: Host: %s Username: %s Password: %s 

The first printf seems to work, but the second has the wrong data. What have I done wrong?

+4
c string arrays pointers malloc
source share
2 answers

The problem is that you are returning a pointer to an array that is on the stack. userDetailsHolder is allocated on the stack and is not available after the function returns.

You can use malloc again to allocate the array itself, and then it will be available after the function returns.

+7
source share

Also, remember to allocate strlen(s)+1 bytes for strings. C lines end with a zero byte, and you need to make sure that there is room for this.

+3
source share

All Articles