-1

Given the following I am getting a segmentation fault and I am not sure if it is because I am testing against a pointer or other issue.

What is the correct way to test if the 4th character is a comma?

string is read from fifo abc,def,xyz

char in[BUFFER] = {'\0'};
if ((in_fl = open(*fifofile, O_RDONLY)) == -1)
    {
     while (read(in_fl, in, BUFFER)>0) {
      doParseInput(&in);
    }


void *doParseInput(char *inputread){
//copy string to use later....
 char* theParsedString = calloc(strlen(inputread)+1, sizeof(char));
 strcpy(theParsedString , inputread);
 if (strcmp(theParsedString[3], ",") == 0){ //causes seg fault

I have also tried using the passed string directly, but also seg fault

if (strcmp(inputread[3], ",") == 0){ //causes seg fault
art vanderlay
  • 2,341
  • 4
  • 35
  • 64
  • `if (inputread[3] == ',') {` is how you compare a *char*. `strcmp()` is for comparing *strings* (sequence of chars terminated with a null byte). – P.P Jan 18 '17 at 14:38
  • See this related [question](https://stackoverflow.com/questions/10490636/compare-between-a-char-in-a-string-to-a-given-char). Not really a duplicate since you are asking for a C solution but the accepted answer there is also C. – qwattash Jan 18 '17 at 14:41
  • 1
    Possible duplicate of [Compare between a char in a string to a given char](http://stackoverflow.com/questions/10490636/compare-between-a-char-in-a-string-to-a-given-char) – qwattash Jan 18 '17 at 14:42
  • Be sure you read enough into `in` (your buffer): if you read only 3 chars, you can't test the 4th. Then, use `doParseInput(in)` without ampersand. Then, compare like `inputread[3] == ','`. – linuxfan says Reinstate Monica Jan 18 '17 at 14:55
  • What kind of crappy compiler let this code compile? – Lundin Jan 18 '17 at 15:01

2 Answers2

1

To pass a buffer to a function, don't use &.
Instead:

doParseInput(in);

To compare the 4th character of a buffer (index == 3):

if (theParsedString[3] == ','){ 

(Notice the single-quotes, meaning Character-Value, rather than the double-quotes, which would mean "String")

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • can you expand or point to some docs on "why" not to use the & to pass a buffer. Using both with `&` and without works, I am interested to understand the good practice behind not using it, thx Art – art vanderlay Jan 18 '17 at 14:50
0

First, you're passing the wrong type of argument to doParseInput. It expects a char * but you're passing it a char (*)[]. Your compiler should have warned you of this.

The other issue is that you're using a string comparison to check a single character. You need to use a character constant (i.e. use single quotes not double quotes) and compare that against the array member directly.

if (theParsedString[3] == ',') {
dbush
  • 205,898
  • 23
  • 218
  • 273