[英]Creating a dynamic char array
我試圖在一個文件中讀取並將單詞存儲到動態char數組中。 現在我收到一個Segmentation fault(core dumped)錯誤。
我已經嘗試使用strdup()和strcpy()仍然得到相同的錯誤
char ** array;
int main(int argc, char * argv[]){
int size = 0;
int i;
FILE * file;
char * line;
size_t len;
ssize_t read;
file = fopen("wordsEn.txt", "r");
if(file == NULL){
printf("Error coudl not open wordsEn.txt\n");
return -1;
}
while((read = getline(&line, &len, file)) != -1){
size++;
}
array = (char **) malloc((sizeof(char *) * size));
rewind(file);
i = 0;
while((read = getline(&line, &len, file)) != -1){
//strcpy(array[i], line);
array[i] = strdup(line);
i++;
}
for(i = 0; i < size; i++){
printf("%s", array[i]);
}
}
我期待例如array [0]返回字符串'alphabet'
我收到了分段錯誤(核心轉儲)錯誤。
每次你必須將行重置為NULL並且len每次重置為0時,通過getline獲取新分配的行的警告,例如:
while(line = NULL, len = 0, (read = getline(&line, &len, file)) != -1){
注意你不必讀取文件的兩倍,你可以使用malloc然后realloc來增加(真正的)動態數組的大小
一份提案 :
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char ** array = malloc(0);
size_t size = 0;
FILE * file;
char * line;
size_t len;
ssize_t read;
file = fopen("wordsEn.txt", "r");
if(file == NULL) {
printf("Error coudl not open wordsEn.txt\n");
return -1;
}
while (line = NULL, len = 0, (read = getline(&line, &len, file)) != -1){
array = realloc(array, (size+1) * sizeof(char *));
array[size++] = line;
}
free(line); /* do not forget to free it */
fclose(file);
for(size_t i = 0; i < size; i++){
printf("%s", array[i]);
}
/* free resources */
for(size_t i = 0; i < size; i++){
free(array[i]);
}
free(array);
return 0;
}
編譯和執行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall ar.c
pi@raspberrypi:/tmp $ cat wordsEn.txt
turlututu foo
bar
loop
pi@raspberrypi:/tmp $ ./a.out
turlututu foo
bar
loop
pi@raspberrypi:/tmp $
在valgrind下執行:
pi@raspberrypi:/tmp $ valgrind ./a.out
==13161== Memcheck, a memory error detector
==13161== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==13161== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==13161== Command: ./a.out
==13161==
turlututu foo
bar
loop
==13161==
==13161== HEAP SUMMARY:
==13161== in use at exit: 0 bytes in 0 blocks
==13161== total heap usage: 11 allocs, 11 frees, 5,976 bytes allocated
==13161==
==13161== All heap blocks were freed -- no leaks are possible
==13161==
==13161== For counts of detected and suppressed errors, rerun with: -v
==13161== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.