I meet one strange problem while using gcc for c lib in strcpy and strtol function. Test on two situation and get the very different results.
//#The bad code is "res=68"
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int main() {
char buf[10];
char* endptr;
int x;
int res;
memset(buf, 0, sizeof(buf));
res=0;
strcpy(buf, "a678b");
while (*(buf) != '\0') {
x = strtol(buf, &endptr, 10);
if (x == 0) {
strcpy(buf, (endptr + 1));
}
else {
strcpy(buf, endptr);
}
res+= x;
}
printf("%d", res);
return 0;
}
After change to the following area, it can get the right value: 678. But, why?
while (*(buf) != '\0') {
x = strtol(buf, &endptr, 10);
if (x == 0) {
memset(kk, 0, sizeof(kk)); // add this
strcpy(kk, (endptr + 1));// add this
strcpy(buf, kk);
}
else {
strcpy(buf, endptr);
}
res+= x;
}