suchacoolguy
suchacoolguy

Reputation: 61

Getting trash value from array even though I initialized it

"Complete the solution so that the function will break up camel casing, using a space between words."

I attached the error message image below. I think this is because of wrong memory access, but I did initialize the temp array so I thought there wouldn't be this kind of problem. Can anyone let me know why this happened?

#include <stddef.h> // NULL
#include <string.h>
#include <stdlib.h>

//returned buffer should be dynamically allocated and will be freed by a caller
char* solution(const char *camelCase) {
  char* res;
  res = (char*)malloc(sizeof(char) * 100);
  
  while(*camelCase) {
    if (*camelCase >= 'A' && *camelCase <= 'Z') {
      strcat(res, " ");
      char temp[2] = {*camelCase, '\0'};
      strcat(res, temp);
    }
    else {
      char temp[2] = {*camelCase, '\0'};
      strcat(res, temp);
    }
    camelCase++;
  }
  return res;
}

enter image description here

Upvotes: 0

Views: 66

Answers (1)

dbush
dbush

Reputation: 223689

The memory returned by malloc is uninitialized. So when you call strcat on res, it is reading uninitialized memory looking for a terminating null byte. This can also potentially read past the end of allocated memory. Both can trigger undefined behavior.

Add a null byte to the start of the buffer to make it an empty string. Then you can append to it.

res = malloc(sizeof(char) * 100);
res[0] = 0;

Upvotes: 3

Related Questions