![](/img/trans.png)
[英]Segmentation fault when trying to allocate memory for a string via a pointer-to-pointer function call
[英]segmentation fault when trying to allocate memory for a string in a struct
解決必須將文件中的數據讀取到結構中的問題。
該文件經過組織,以便有一個名稱,幾行ASCII圖片(以#結尾)和一個等級。 這是一個例子
Sample Name
( S )
( S )
# 5
我有這樣的結構設置:
typedef struct
{
char* name;
char* art;
int rating;
}CASE;
我的問題是,當我嘗試為以下代碼中的名稱字符串動態分配內存時,我始終遇到segmentation fault
:
/*FPin is file pointer to the txt file and all is the array of structs*/
void readFile(FILE* FPin, CASE** all)
{
CASE* walker = *all;
int count = 0;
char buffer[160];
char* bufferPtr = buffer;
char nameBuffer[100];
/*Reads in the name*/
while(fscanf(FPin, "%[^\n]", nameBuffer))
{
printf("string is %s\n", nameBuffer);
walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer+1))); /*ERROR*/
strcpy(walker->name, nameBuffer);
}
return;
}
我記下了我認為上面代碼中的錯誤的位置,因為一旦添加了該行,便開始獲取它。
我基本上是從文本中讀取一個名稱到nameBuffer(數組)中,然后使用strcpy將此名稱復制到該結構中。 有關如何解決此問題的任何建議?
感謝您的光臨。
我將在下面包括我的其余資料:
int main (void)
{
CASE* all;
FILE* FPin;
if((FPin = fopen("art.txt", "r")) == NULL)
{
printf("Error opening file.");
exit(100);
}
allocateStructMem(&all);
readFile(FPin, &all);
fclose(FPin);
return 0;
}
void allocateStructMem (CASE** all)
{
if((*all = (CASE*)malloc(sizeof(CASE)*1000)) == NULL)
{
printf("Fatal memory error!\n");
exit(1);
}
return;
}
strlen(nameBuffer + 1)
strlen(nameBuffer)+1
當您all
分配時,還必須執行以下操作:
int allocateStructMem(CASE **all)
{
/* +----- Note. And no need to cast as malloc returns (void *)
| */
if((*all = malloc(sizeof(CASE*) * 1000)) == NULL)
為了防止溢出,您必須限制fscanf
的長度,即:
while (fscanf(FPin, "%99[^\n]", nameBuffer) == 1) {
1
確保您已實際將某些內容讀入nameBuffer。
而且strcpy
不會填充-但您可能知道這一點。
將+1移到方括號之外是否有幫助?
walker->name = (char*)malloc(sizeof(char)*(strlen(nameBuffer)+1)); /*ERROR*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.