0

I was doing this Highest Scoring Word kata on codewars which is to find the highest scoring word out of a string that is seperated by spaces and I kept getting the warning in the title even though I passed all the tests. Why does this happen?

I wrote in C and this is my code


#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/*
** @param str: a C-string containing only lowercase letters and spaces (' ')
** @return:    a C-string allocated on the heap containing the highest scoring word of str
*/
int calculateScore(char* word) {
  int score = 0;
  int length = strlen(word);
  for (int i = 0; i < length; i++) {
    char ch = *(word + i);
    score += ch;
  }
  return score;
}

char  *highestScoringWord(const char *str)
{
  char *word = malloc(sizeof(str)/sizeof(char));
  char *token = malloc(sizeof(str)/sizeof(char));
  int score = 0;
  char *rest = malloc(sizeof(str)/sizeof(char));
  strcpy(rest, str);
  token = strtok_r(rest, " ", &rest);
  
  while (token) {
    int newscore = calculateScore (token);
    if (score < newscore) {
      score = newscore;
      word = token;
    }
    token = strtok_r(rest, " ", &rest);
  }
  return word;
}

  • `malloc(sizeof(str)/sizeof(char));` ==> `malloc(strlen(str) + 1);`. Why divide by `sizeof(char)`? – mch Sep 09 '22 at 07:34
  • `char *word = malloc(...` and later `word = token;` is a memory leak. The same for `token` and because you return a pointer somewhere into the middle of `rest` the caller will not be able to `free` that too. – mch Sep 09 '22 at 07:37
  • ^ plus also I believe the 2nd call to `strtok_r` should be passing a `null` as the 1st parameter. – Tibrogargan Sep 09 '22 at 07:39
  • Do you think you need the "reentrant" version of `strtok( )`? Do you know what that word means? – Fe2O3 Sep 09 '22 at 07:44
  • That code under-allocates *and* leaks like a sieve. – WhozCraig Sep 09 '22 at 07:47
  • 1
    @Gerhardh [I don't think I am](https://man7.org/linux/man-pages/man3/strtok.3.html). – Tibrogargan Sep 09 '22 at 08:02
  • @Tibrogargan you are right. I missed that the variable was set to `NULL` in the example from manpage. Sorry. – Gerhardh Sep 09 '22 at 08:24

0 Answers0