gpt4 book ai didi

使用指向 uint64_t 的指针复制 C 中的自定义字符串会导致段错误

转载 作者:行者123 更新时间:2023-11-30 15:46:54 27 4
gpt4 key购买 nike

正如标题所说,每当我尝试复制字符串(使用我自己的字符串类型和库)时,我都会遇到段错误。根据调试器的说法,它发生在源代码的第 29 行(调用 s_strcpy4() 的地方),该行转到 sstring.h 中带有“_dest[i] = _sour[i];”的行。 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;
}

最佳答案

_dest[i] = _sour[i]; 应该 _dest[i/8] = _sour[i/8];

或类似的东西。

代码还有很多其他问题。例如,在需要正确对齐指针的体系结构上,尝试访问不以八的倍数地址开头的一组八个字符将导致总线错误。

我假设您这样做是为了练习,而不是在生产中使用。只需使用 memcpy()

关于使用指向 uint64_t 的指针复制 C 中的自定义字符串会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17914976/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com