Cerumersi
Cerumersi

Reputation: 97

How to reset the value of a C string pointer?

I am trying to use the same pointer twice, like this:

void* pointer = (char*) malloc(15);
pointer = "Patricia";
printf("%s", pointer);
pointer = "John";
printf("%s", pointer);

but the output I'm receiving is this:

Patricia
Johnicia

Here is the full code (the client script is a python script so I don't find it appropriate to post here)(the John and Patricia are examples of usernames the client might enter):

#define MAXCLIENTS 256
#define MAXMSG 269

void forward(int clientslist[MAXCLIENTS], char* msg) {
    int x;
    for (x=0; x < MAXCLIENTS;  x++){
        send(clientslist[x], msg, MAXMSG, 0);
    }
    return;
}

int main(){

    #define PORT 5943

    int s = socket(AF_INET, SOCK_STREAM, 0);
    int clients[MAXCLIENTS];
    int clientcounter = 0;

    fd_set socketlist, readlist;
    FD_ZERO(&socketlist);
    FD_SET(s, &socketlist);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = INADDR_ANY;

    bind(s, (struct sockaddr*) &server, sizeof(server));
    listen(s, MAXCLIENTS);
    int clientsocket;
    int i;
    void* msg = (char *) malloc(MAXMSG);
    void* usr = (char*) malloc(10);


    while (1){
        readlist = socketlist;
        select(FD_SETSIZE, &readlist, NULL, NULL, NULL);
        for (i=0; i<FD_SETSIZE; i++){
            if(FD_ISSET(i, &readlist)){
                if (i == s){
                    clientsocket = accept(s, NULL, NULL);
                    FD_SET(clientsocket, &socketlist);
                    clients[clientcounter] = clientsocket;
                    clientcounter++;
                    recv(clientsocket, usr, 10, 0);
                    printf("Connection received from %s\n", usr);

                } else {
                    recv(i, msg, MAXMSG, 0);
                    forward(clients, msg);
                }
            }

        }
    }
    return 0;
}

How do I fix this?? Thanks

Upvotes: 0

Views: 414

Answers (1)

William Pursell
William Pursell

Reputation: 212464

recv returns the number of bytes read, and you just need to add a null terminator. eg:

ssize_t rc;
rc = recv(clientsocket, usr, 9, 0);
if( rc >= 0 )
    usr[rc] = '\0';

Note that I've reduced the length argument in the call to recv to ensure that there is space for the terminator. If you expect to receive messages of length 10, you would want to allocate at least 11 bytes for usr. However, with buffers that small, it would probably be cleaner to use an array and do:

char usr[11];
ssize_t rc;
rc = recv(clientsocket, usr, sizeof usr - 1, 0);
if( rc >= 0 )
    usr[rc] = '\0';

Upvotes: 2

Related Questions