【发布时间】:2014-02-08 05:33:02
【问题描述】:
我编写了一个代码,它使用 gcc 内联汇编获取字符串的子字符串。但是当我想获取长度为 8 的子字符串时总是会遇到问题。这是代码
static inline char * asm_sub_str(char *dest, char *src, int s_idx, int edix)
{
__asm__ __volatile__("cld\n\t"
"rep\n\t"
"movsb"
:
:"S"(src + s_idx), "D"(dest), "c"(edix - s_idx + 1)
);
return dest;
}
int main(int argc, char *argv[])
{
char my_string[STRINGSIZE] = "abc defghij";
char asm_my_sub_string[STRINGSIZE];
int sidx,eidx;
sidx = 0;
eidx = 5;
char *d1 = asm_sub_str(asm_my_sub_string, my_string, sidx, eidx);
printf("d1[%d-%d]: %s\n",sidx, eidx, d1);
sidx = 0;
eidx = 7;
d1 = asm_sub_str(asm_my_sub_string, my_string, sidx, eidx);
printf("d1[%d-%d]: %s\n",sidx, eidx, d1);
sidx = 0;
eidx = 9;
d1 = asm_sub_str(asm_my_sub_string, my_string, sidx, eidx);
printf("d1[%d-%d]: %s\n",sidx, eidx, d1);
}
这是输出
d1[0-5]: abc de
d1[0-7]: abc defg?
d1[0-9]: abc defghi
有什么想法吗??????
感谢您的回复。这是子字符串的c代码,我忘了空终止字符串。感谢仙人掌和bbonev!希望其他人可以从这个帖子中学习。
static inline char * sub_str(char *dest, char *src, int s_idx, int edix)
{
int length = edix - s_idx + 1;
int i;
for(i = 0; i < length; i++)
{
*(dest + i) = *(src + s_idx + i);
}
*(dest + length) = '\0';
return dest;
}
【问题讨论】:
-
哪里不工作..?如果有什么我认为是因为您没有正确地以空值终止字符串,这意味着它完全可以工作有点幸运。
-
非常感谢。但有趣的是,只有当 eidx-sidx = 8 时才会出现问题,这意味着所需的子字符串的长度为 8。否则它很幸运。我还是想不通。
标签: c gcc assembly inline-assembly