wokoro douye samuel
wokoro douye samuel

Reputation: 2374

Unexpected return value from string

I am trying to get just the phone number out of the string passed into getPhoneNumber(char[] str), but for some reason, i get some random character appended to it each time i run the code, please i need help.

source code

#include <stdio.h>
#include <string.h>


char* getPhoneNumber(char str[]);

int main(){

  getPhoneNumber("AT+CMGR=5 \n+CMGR: \"REC READ\",\"+9349036332058\",\"samuel\",\"17/03/31,20:44:52+04\"\nHOW THINS fa OK");

  return 0;
}

char* getPhoneNumber(char str[]){

  char *temp = strchr(str, ',')+2;
  const unsigned short len1 = strlen(temp);

  printf("value in temp : %s\n\n",temp);

  char *strPtr = strchr(temp, '\"');
  const unsigned short len2 = strlen(strPtr);

  printf("value in strPtr : %s\n\n",strPtr);
  int phone_num_len = len1-len2;

  char phone_num[phone_num_len];

  strncpy(phone_num, temp,phone_num_len);

  printf("Phone number : %s",phone_num);

}

I also printed out individual values of temp and strPtr for debugging purposes, but the returned values seems ok. The output of the program is shown in the image below.

enter image description here

Upvotes: 2

Views: 139

Answers (2)

dbush
dbush

Reputation: 225344

You're not setting aside enough space for phone_num. As a result, printf is reading past the end of the array. This invokes undefined behavior. That is why you see extra characters when running locally but it appears to work fine on ideone (it also appears to run fine for me).

You need one more byte for the null terminating character for the string. Also, you need to manually add that null terminator since the strncpy function won't do it for you since there's no null terminator within phone_num_len bytes of temp.

char phone_num[phone_num_len+1];

strncpy(phone_num, temp,phone_num_len);
phone_num[phone_num_len] = '\0';

Upvotes: 5

Scott Hunter
Scott Hunter

Reputation: 49920

From the man page for strncpy(char * dst, const char * src, size_t len):

If src is less than len characters long, the remainder of dst is filled with `\0' characters. Otherwise, dst is not terminated.

So it is not, as you seem to expect, terminating the "string" you are copying.

Upvotes: 1

Related Questions