Readers: 15
7 entries, 1 page |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
int *getinp(const char *filename);
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
int *foo = getinp(argv[1]);
return 0;
}
int *getinp(const char *filename) {
FILE *fd = fopen(filename, "r");
if (fd == NULL) {
fprintf(stderr, "Couldn't open %s for reading\n", filename);
exit(EXIT_FAILURE);
}
int pos = 0;
int size = 64;
int *arr = malloc(size * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
char c;
while ((c = fgetc(fd)) != EOF) {
arr[pos] = c;
pos++;
if (pos >= (size - 1)) {
size *= 2;
if (realloc(arr, size * sizeof(int)) == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
}
}
arr[pos] = '\0';
fclose(fd);
return arr;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ gdb --args ./a.out big.bad.testfile
[gdb]> run
Starting program: /home/user/a.out big.bad.testfile
Program received signal SIGSEGV, Segmentation fault.
0x08048646 in getinp (filename=0xbf9c75b1 "big.bad.testfile") at fail.c:34
34 arr[pos] = c;
[gdb]> p size
$1 = 65536
[gdb]> p pos
$2 = 33700
[gdb]> p arr[pos-1]
$3 = 9
[gdb]> p arr[pos]
Cannot access memory at address 0x806b000
1
2
3
4
5
size *= 2;
if (realloc(arr, size * sizeof(int)) == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
1
2
3
4
5
6
size *= 2;
arr = realloc(arr, size * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Not enough memory\n");
exit(EXIT_FAILURE);
}
Quotevoid *realloc(void *ptr, size_t size);
[...]
On success a pointer to the memory block is returned (which may be in a different location as before). On failure or if size is zero, a null pointer is returned.
Quotesize *= 2; wird schnell groß, dass ist dir klar, oder? würde es auch fast so schreiben size += size;
FoolAck+2009-01-27 08:29:25--Das das rechnerisch das Gleiche ist, ist dir klar, oder?
esskar+2009-01-27 07:59:51--size *= 2; wird schnell groß, dass ist dir klar, oder? würde es auch fast so schreiben size += size;
murphy+2009-01-27 16:10:41--Es ist aber sinnvoll, den Speicherpuffer exponentiell zu vergroessern, um die Anzahl der Allokationen und die Fragmentierung des Speichers moeglichst gering zu halten. Fast jede Implementation dynamisch wachsender Arrays arbeitet so.
7 entries, 1 page |