Pages

Tuesday, June 11, 2019

SIGABRT from malloc

Any ideas why malloc is failing?  Excel exports empty cells as just a tab, which is right, but strtok sees two tabs as end of tokens (as you would expect) but I need to replace \t\t with \t \t to make sure tha every cell is prsent in my char* fields array.

/* Replace one substring with another substring through the inputString.
   This mallocs a new string, so you are required to free this string when
   done */
char* stringReplace (char* inputString, char* searchString, char* replaceString)
{
  int i;
  int j;
  int len;
  int addedBlanks = 0;
  char* returnString;

  printf("inputString=%s\n", inputString);
  /* how many added blanks? */
  for(i = 0; i       if(0 == strncmp(inputString+i, searchString, strlen(searchString)))
       addedBlanks++;
  /* allocate larger destination string */
  if(addedBlanks == 0)
    returnString = inputString;
  else
    {
      len = strlen(inputString);
      returnString = malloc(len + addedBlanks+10);
      for(i = 0; i < strlen(inputString); i++)
{
  if(0 == strncmp(inputString+i, searchString, strlen(searchString)))
    {
    strcpy(returnString+j, replaceString);
    j += strlen(replaceString);
    i += strlen(searchString);
    }
  else
    returnString[j++] = inputString[i];
}
    }
  free(inputString);
  printf("returnString=%s\n", returnString);
  return(returnString);
}

No comments:

Post a Comment