[英]What is causing this segfault?
[自昨天以來,對該問題進行了大量編輯。 我正在更新以澄清問題。]
調用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';
}
有人可以告訴我為什么會出現段錯誤嗎?
除非代碼與問題的比率低於某個任意閾值,否則我無法發布此問題。 因此,下面是《愛麗絲夢游仙境》的第一段,供您考慮。
愛麗絲開始不厭其煩地坐在姐姐在銀行旁,無事可做:她曾一兩次偷窺妹妹正在讀的書,但里面沒有照片或談話,“還有什么?是用書嗎?”愛麗絲想,“沒有照片或談話?”
調用func
,將在main
傳遞局部變量p
的副本 。 然后,此副本分配malloc
在編輯區func
。 main
的原始p
從未修改,因此其內容保持未定義狀態,當printf
引用p
以便打印字符串時,會導致分段錯誤。
您可能希望func
返回指向新分配的區域的char*
。
您通過值將參數傳遞給函數。 所以根據功能聲明
void func(char* p);
參數p是函數的局部變量,在退出函數后將被銷毀。 局部變量的任何更改都不會影響參數。
您可以通過以下方式定義函數
char * func(){
unsigned count = 10;
char *p = (char*) malloc(sizeof(char)*(count+1));
//p is given a string after this, but problem is the above line.
return p;
}
並稱其為
p = funct();
要么
void func(char ** p){
unsigned count = 10;
*p = (char*) malloc(sizeof(char)*(count+1));
//p is given a string after this, but problem is the above line.
}
並稱其為
func( &p );
問題在於:
*p[i] = curr->ch;
應該:
(*p)[i] = curr->ch;
您想訪問p
指向的第i
個字符。 不取消引用指針數組中的第i
個指針。
*p[i] = '\\0';
同樣的問題*p[i] = '\\0';
后來。
另外,您沒有分配足夠的空間,因為您的循環寫入了count + 1
字符,然后又編寫了一個額外的空終止符,因此您應該malloc count + 2
或調整循環以在i<count
而不是i<=count
。 (可能是后者)。
另外,在取消引用前檢查curr != NULL
很有用,這樣,如果您確實有一個錯誤的錯誤,那么您就不會得到不確定的行為。
免責聲明 :在回答此問題時, 問題甚至沒有包括問題的真正原因 ,並且代碼不足,因此這兩個建議都是唯一可能出錯的問題。 現在,OP在夜間某個時間發布了他的實際代碼,該代碼已失效。 出於明顯的原因,請不要基於此投票。
--
刪除(char*)
演員表。 您肯定會收到“賦值使整數不帶強制轉換的指針”警告。
然后#include <stdlib.h>
因此您實際上可以使用malloc
&co,而不會因不匹配的函數簽名而導致未定義行為。
編輯:如果在main
調用func
之前沒有聲明func
,也會出現類似的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.