Reputation: 1061
I am trying to brush up on my C and I have the following code it works when I use the i offset but not with hold++, I don't see why I thought they did same thing? Here is the version I can't get to work:
char* reversestring2(char* s)
{
int mysize = strlen(s);
char* temp = s+mysize;
//I do +1 for the terminator
char* hold = (char*) malloc(mysize+1);
while(temp > s)
{
*(hold) = *--temp;
hold++;
}
*(hold++) = '\0';
//printf("pre cpy %s", hold);
strcpy(s,hold);
//printf("%s", hold);
return(s);
}
Thanks
char* reversestring(char* s)
{
int mysize = strlen(s);
char* temp = s+mysize;
char* hold = (char*) malloc(mysize+1);
int i=0;
while(temp > s)
{
*(hold+i) = *--temp;
//hold++;
i++;
}
*(hold+i) = '\0';
//printf("pre cpy %s", hold);
strcpy(s,hold);
//printf("%s", hold);
return(s);
}
int main()
{
//printf("%s\n", "you suck");
char test[100] = "you suck";
reversestring(test);
printf("%s\n", test);
//or
char* hold = (char*) malloc(100);
hold = reversestring(test);
if(hold == NULL)
printf("%s\n", "ERROR");
printf("Second run: %s\n", hold);
}
Upvotes: 0
Views: 112
Reputation: 4277
hold is a pointer variable which points to the beginning (first char element) of the block of memory that you allocate. hold++ will make it point to the next char in that block of memory. hold = hold + 5 will make it point to the 6-th char in that block of memory and so on.
if you want to use hold++ instead, you need to delete i++, and replace *(hold+i) = *--temp; with *hold = *--temp; if you want so.
*hold is equivalent to *(hold + 0), I think you get the idea
Upvotes: 0
Reputation: 99094
When you use hold++
, the pointer hold
advances to the end of the allocated array. Then you do this:
*(hold+i) = '\0';
which inserts a value into memory outside the bounds of the allocated space (e.g 200 steps from the beginning of an array of length 100), which causes undefined behavior. Then this:
strcpy(s,hold);
which copies who-knows-what from uncontrolled memory into the string.
Upvotes: 1