正如标题所说,每当我尝试复制字符串(使用我自己的字符串类型和库)时,我都会遇到分段错误。根据调试器,它发生在源代码的第 29 行(调用 s_strcpy4() 的位置),它转到 sstring.h 中带有“_dest[i] = _sour[i];”的行。在崩溃时,我似乎不时有一些不同的价值,但有时会坚持一个价值(尚不知道为什么)。在撰写本文时,它卡在了 16896。
任何人都知道我可能在哪里导致代码中的段错误?
来源.c
#include "sstring.h"
#include <string.h>
#include <stdio.h>
#include <time.h>
int main(void) {
s_string ss1,
ss2;
long long int start, end;
struct timespec time;
FILE *LoremIpsum;
s_init(&ss1, NULL, 65536);
s_init(&ss2, NULL, 65536);
LoremIpsum = fopen("Lorem ipsum", "r");
if(LoremIpsum == NULL) {
perror("Error opening file ");
return 1;
}
fgets(ss2.string, 65536, LoremIpsum);
if(fclose(LoremIpsum) == EOF) {
perror("Error closing file ");
return 2;
}
s_strcpy4(&ss1, &ss2);
return 0;
}
字符串.h
#include <stdlib.h>
#include <stdint.h>
enter code here
typedef struct {
int length;
char *string;
} s_string;
s_string *s_init(s_string *str, char *array, size_t num) {
int i;
if(str == NULL)
str = malloc(sizeof(s_string));
if(array == NULL) {
(*str).length = num;
if(num != 0)
(*str).string = malloc(num);
} else {
if(num == 0) {
(*str).string = NULL;
for(i = 0; array[i] != '\0'; i++) {
(*str).string = realloc((void *)(*str).string, i + 1);
(*str).string[i] = array[i];
}
(*str).length = i;
} else {
(*str).string = (char *)malloc(num);
(*str).length = num;
for(i = 0; i < num; i++)
(*str).string[i] = array[i];
}
}
return str;
}
s_string *s_strcpy4(s_string *__restrict__ destination, const s_string *__restrict__ source) {
int i;
long long *_dest = (long long *)(destination->string),
*_sour = (long long *)(source->string);
for(i = 0; i < source->length - 8; i+=8)
_dest[i] = _sour[i];
for( ; i < source->length; i++)
destination->string[i] = source->string[i];
destination->length = i;
return destination;
}