SE_1991
SE_1991

Reputation: 675

Pointer to char array only contains last few letters of content

I have a program that forks (it's working as a C socket server) and that all works fine. Before I fork, I assign shared memory for two of my structs, which also works fine when I do this later on:

abc->results = "Heyyy";

When I access abc->results in another child process, I get "Heyyy" returned. However, my C program builds up a message then needs to display that message:

//Results msg
char msg[46];
strcpy(msg, " {0,");
strcat(msg, cScore1);
if(score1 > 80) {
    strcat(msg, ",Pass},");
} else {
    strcat(msg, (",Fail},"));
}
strcat(msg, "{1,");
strcat(msg, cScore2);
if(score2 > 80) {
    strcat(msg, ",Pass},");
} else {
    strcat(msg, (",Fail},"));
}
strcat(msg, "{2,");
strcat(msg, cScore3);
if(score3 > 80) {
    strcat(msg, ",Pass}");
} else {
    strcat(msg, (",Fail}"));
}

abc->results = msg;

When changed to this, I get random symbols appearing (weird squares and X's). Occasionally I can see the last } before the weird symbols. My guess would be that it has something to do with the size of abc->results, but it's a pointer:

typedef struct myStruct {
char* results;
} structA;

I'm fairly new to C, so any help is greatly received.

Edit:

Forgot one more bit of crucial information. The correct message is displayed when I write to the socket in the same process:

abc->results = msg;

printf(msg);
printf("\n");

n = write(sock, abc->results, 47);

The printf and write display the correct results. It's when I use it again in the child process it breaks (in a different function, writing to a different client connection):

n = write(sock, abc->results, 47);

The write function params are exactly the same as above, so I'm very confused why it isn't working!

Edit again:

I've changed the msg to char * msg = malloc(45);. However, now when I use it in the child process I get nothing:

void myFunction(int sock) {
int n;

n = write(sock, abc->results, 47);
//This is not displayed either!
printf("\nResults:");
printf(abc->results);
printf("\n");

if (n < 0){
    perror("Error writing to the socket");
    exit(1);
} else {
    printf("Results sent\n");
}
}

Upvotes: 1

Views: 56

Answers (1)

Bathsheba
Bathsheba

Reputation: 234685

abc->results = "Heyyy"; is assigning a string literal which lasts for the lifetime of the program.

abc->results = msg; is immediately invalidated once msg goes out of scope at the end of your function.

This is why the first case works but the second one doesn't. In the latter case the behaviour of your program is undefined.

The fix is trivial: allocate memory for msg using malloc.

Upvotes: 3

Related Questions