[英]Segmentation fault in accessing & modifying string (char*) array in C
我一直在嘗試編譯一段時間的程序上嘗試分段,並在嘗試了許多方法(例如重新編程我現在使用的數據結構)后遇到分段錯誤(gdb在回溯線上打印“ ??”) )我仍然不斷遇到段錯誤,盡管現在它給了我一行(我在此處添加了評論)。
多次運行getMains()來標記同一文件中的不同行。
我希望mains是一個大小為4的數組,但是當將其作為“ char * mains [4]”傳遞時,II嘗試將其傳遞給一個數組(*)[4]時遇到了編譯錯誤,而我之前從未處理過(剛開始使用C)。 我假設如果嘗試訪問未使用的任何部分,可能會出現問題,但問題是在初始化數組的索引時發生的。
我正在嘗試使用的代碼,其中“ char *** mains”參數從單獨的函數“ runner”中獲取一個&(char **),我希望對其進行編輯,以便於查看“跑步者”中的內容:
bool getMains(FILE * file, char *** mains)
{
char line[256];
int start = 0;
char * token;
const char * mainDelim = "\t \n\0", * commDelim = "\n\t\0";
if(fgets(line, sizeof(line), file) == NULL)
return false;
while(line[0] == '.')
if(fgets(line, sizeof(line), file) == NULL);
return false;
if(line[0] == '\t' || line[0] == ' ')
{
(*mains)[0] = " ";
start = 1;
}
token = strtok(line, mainDelim);
int i;
for(i = start; token != NULL; ++i)
{
(*mains)[i] = strdup(token); // <- gdb: Segmentation Fault occurs here
if(i % 3 == 2)
token = strtok(NULL, commDelim);
else
token = strtok(NULL, mainDelim);
}
free(token); // Unsure if this was necessary but added in case.
return true;
}
/* Snippet of code running it... */
void runner(FILE * file) {
char ** mains;
if(!getMains(*file, &mains))
return;
while(strcmp(mains[1], "END") != 0){
/* do stuff lookinig through indices 0, 1, 2, & 3 */
if(!getMains(*file, &mains))
break;
}
}
關於此的任何提示還是通過其他功能通常可以安全地修改數組?
我應該將getMains()更改為“ getMains(FILE * file,char ** mains [4]);” 並通過一個&“ char * mains [4]”)使其成為所需的設置大小? 還是會產生錯誤?
您需要為市電分配內存,它應如下所示:
char ** mains;
mains = malloc(some number N * sizeof(char*));
如果不使用strdup,則需要這樣的東西,它會為您分配內存:
for (int i = 0; i < N; ++i) {
mains[i] = malloc(some number K);
}
在所有情況下,請不要忘記對從malloc
或strdup
收到的每個指針進行free
調用。 如果程序在調用free
之后立即結束,則可以跳過此部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.