I'm sorry if my code is garbage but I wanted to experiment with string manipulation on an already dynamically allocated string without losing my original pointer so that when I do go ahead and free up the memory outside of the function I won't be freeing the wrong thing.
The algorithm is as follows:
- Receive a dynamically allocated string containing multiple words
- If there is an even number of words, set the amount of spaces between each word to 2. Otherwise leave it as 1 space.
char* evenNumOfWords(char* str)
{
int spaceCounter = 0; // count the occurrences of space
int spaceIndices[strlen(str)]; // save the index of all space characters to avoid going through the whole array twice
char* endPointer = str + strlen(str);
int length;
for (int i = 0 ; i < strlen(str) ; i++)
{
if(str[i] == ' ')
{
spaceIndices[spaceCounter] = i;
spaceCounter++;
}
}
if (spaceCounter % 2 == 1) { // if there is an odd number of spaces there's an even number of words
for (int i = 0 ; i < spaceCounter ; i++)
{
length = (int)(endPointer - str);
memmove(str + spaceIndices[i] * sizeof(char) + 1, str + spaceIndices[i] * sizeof(char), length - spaceIndices[i] + 1); // move the string 1 byte forward starting from the place where there's a space
endPointer++;
str[spaceIndices[i]] = ' ';
}
}
return str;
}
Perhaps my logic is entirely incorrect but my main question is, can I actually write on the memory that I moved my data away from with memmove? Because I'm getting "code 138 (interrupted by signal 10: SIGBUS)" which after Googling I found it's caused by writing on non-writable memory.
Thanks in advance!
The only difference between
memmoveandmemcpyis thatmemmovecopies the bytes non destructively. That is to say, if the source and destination areas overlap,memmovewill work fine butmemcpymay not.Your problem is likely due to passing a constant string into your function. If you do
the string passed in is a literal and likely to be located in a read only segment.