【发布时间】:2013-07-29 01:58:02
【问题描述】:
正如标题所说,每当我尝试复制字符串(使用我自己的字符串类型和库)时,都会遇到分段错误。根据调试器,它发生在源代码的第 29 行(调用 s_strcpy4() 的位置),它转到 sstring.h 中带有“_dest[i] = _sour[i];”的行。 i 在崩溃时似乎不时具有一些不同的值,但有时会坚持一个值(尚不确定为什么)。在撰写本文时,它一直停留在 16896。
任何人都知道我可能在哪里导致代码中的段错误?
source.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;
}
【问题讨论】:
-
s_init(p, NULL, 0)不会初始化p->string。我不确定这是 问题,但这是 a 问题。 -
谢谢,没意识到。现在它在这种情况下将 p->string 设置为 NULL。
标签: c string segmentation-fault copying