I am working on a project, and for some reason I am not able to get strtol()
to convert a char *
to an integer. I have this code:
int main(int argc, char *argv[]) {
//socket initialization code...
struct sockaddr_in addr;
char *buffer;
receivePacket(&sock, &buffer, &addr); //function i have written to receive a packet
char *temp;
int times = (int) strtol(buffer, &temp, 10);
}
When I run this, times always ends up being 0, and temp returns garbage:
(gdb) print buffer
$1 = 0xbefff648 "1"
(gdb) print times
$2 = 0
(gdb) print temp
$3 = 0xbefff648 "H\366\377\276(\207"
I don't understand why strtol cannot comprehend what I am giving it.
In receivePacket
:
void receivePacket(int *sock, char **buffer, long *tx, struct sockaddr_in *cliaddr) {
//socket related code, initializations, etc.
char temp[10] = { 0 };
n = recvfrom(*sock, temp, 10, 0, (struct sockaddr *) &cliAddr, &clilen);
*buffer = temp;
}
Is this where the problem resides? Thanks.
void receivePacket(int *sock, char **buffer, long *tx, struct sockaddr_in *cliaddr) {
//socket related code, initializations, etc.
char temp[10] = { 0 };
n = recvfrom(*sock, temp, 10, 0, (struct sockaddr *) &cliAddr, &clilen);
*buffer = temp;
}
temp
is a local variable. It ceases to exist when the function returns, leaving *buffer
pointing to some invalid place.