gpt4 book ai didi

c - 将 char* 解析为标记时出现段错误

转载 作者:行者123 更新时间:2023-11-30 19:11:01 25 4
gpt4 key购买 nike

我正在尝试解析任意索引周围的字符串。在我最简单的测试程序中,我可以想出一个输入字符串,我将输入读入其中,然后执行 memcpy 来解析该字符串。

为了测试这一点,我输入“此文本”作为输入。 readInput 是一个函数,我只需调用 getline(&input, &size, stdnin) 并返回输入指针。

int main(){
char *input;
input = readInput();

int parseAround = 4;
char *token1;
char *token2;

memcpy(token1, inputBuffer, 4);
printf("token: %s\n", token1); //prints "this"

memcpy(token1, inputBuffer + (parseAround+1), 4);
//when changed to memcpy(token2,...); segfaults
printf("token: %s\n", token1); //prints "text"


free(input);
return 0;
}

但是,当我将第二个 memcpy 更改为使用 token2 而不是 token1 时,出现段错误。这是为什么?

最佳答案

您很可能需要为 token1 分配内存。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
char *input = NULL;

size_t len = 0;
ssize_t read;

/* Read in the line "Hello world" */
read = getline(&input, &len, stdin);
printf("Retrieved line of length %zu :\n", read);
printf("%s", input);

/* Allocate memory for both parts of the string */
char *token1 = malloc((read+1) * sizeof(char *));
char *token2 = malloc((read+1) * sizeof(char *));

memcpy(token1, input, 6);
printf("token: %s\n", token1); //prints "Hello"

memcpy(token2, (input+6), 5);
printf("token: %s\n", token2); //prints "world"

free(input);
return 0;
}

读入该行,为每个字符串部分分配内存,然后将所需的部分复制到你的s中

关于c - 将 char* 解析为标记时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40774391/

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