gpt4 book ai didi

c - 是什么导致了这个段错误?

转载 作者:行者123 更新时间:2023-11-30 18:40:39 24 4
gpt4 key购买 nike

调用 mygets() 后出现段错误。这是我的代码:

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

typedef struct _charlist{
char ch;
struct _charlist *next;
}charlist;

static struct termios old, new;
void mygets(char** p);
char getche(void);
char getch_(int echo);
void resetTermios(void);
void initTermios(int echo);


int main(void){
char *p;

printf("\nWho loves orange soda?: ");
mygets(&p);
printf("'%s' loves orange soda!", p);
}


void mygets(char** p){
char c;
charlist *root, *curr;
unsigned i, count=0;

root=NULL;

while((c = getche()) != '\n'){

count++;
if(!root){
root = (charlist*) malloc(sizeof(charlist));
root->ch = c;
root->next = NULL;
curr = root;
}

else{
curr
->next = (charlist*) malloc(sizeof(charlist));
curr->next->ch = c;
curr->next->next = NULL;
curr = curr->next;
}
}

//now request string space.
*p = (char*) malloc((count+1)*sizeof(char));

printf("\np is now malloced"); //This line doesn't get printed!

//move linked list into string space.
curr = root;
for(i=0; i<=count; i++){
*p[i] = curr->ch;
curr = curr->next;
}

//null-terminate the string.
*p[i] = '\0';

}

有人可以告诉我为什么会出现段错误吗?

除非代码与问题的比率低于某个任意阈值,否则我无法发布此问题。因此,现在有《爱丽丝梦游仙境》第一段,供大家引用。

Alice was beginning to get very tired of sitting by her sister on thebank, and of having nothing to do: once or twice she had peeped intothe book her sister was reading, but it had no pictures orconversations in it, 'and what is the use of a book,' thought Alice'without pictures or conversation?'

最佳答案

何时 func被调用时,会传递局部变量 p副本main 。然后将此副本分配为 malloc编辑区 func 。原文pmain从未被修改,因此其内容保持未定义,从而在 printf 时导致段错误取消引用p为了打印字符串。

您可能需要func返回 char*指向新分配的区域。

关于c - 是什么导致了这个段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25415835/

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