-
-
Save GeeLaw/47dea7677eb48e1b9896bfe9d006b5f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdio.h" | |
#include "stdlib.h" | |
#include "string.h" | |
#define STRLENS 4 | |
int main(int argc, char **argv) | |
{ | |
char s[] = " a "; | |
char *start, *start2; | |
start = s; | |
while (*start != '\0') start++; | |
--start; | |
char s2[STRLENS + 1]; | |
char *s2p = s2; | |
char flag; | |
while (start > s) | |
{ | |
flag = 0; | |
while (*start == ' ') start--; | |
/* In typical implementation without extra memory protection, | |
** this is likely to print | |
** start - s = -1 [should not be negative] | |
** in the second iteration. | |
** This is undefined behavior, because the pointer start | |
** does not point to any valid object or past-the-end | |
** of an array object. | |
**/ | |
fprintf(stderr, "start - s = %d [should not be negative]\n", | |
(int)(start - s)); | |
while (start >= s && *start != ' ') start--; | |
start2 = start; | |
++start2; | |
while (*start2 != ' ') | |
{ | |
*s2p++ = *start2++; | |
if (flag == 0) flag = 1; | |
} | |
if (flag == 1) *s2p++ = ' '; | |
} | |
*s2p = '\0'; | |
fprintf(stderr, "s2p - s2 = %d [should not exceed %d]\n", | |
(int)(s2p - s2), (int)(STRLENS + 1)); | |
start = s; | |
s2p = s2; | |
while (*s2p != '\0') *start++ = *s2p++; | |
*start = '\0'; | |
printf("%s\n%d\n", s, (int)strlen(s)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment