Bonjour,
J'ai un problème d'allocation mémoire sur le programme C suivant (voir en bas).
Je travaille sur AIX.
Lorsque j'exécute le programme, j'obtiens le résultat suivant :
Et je ne parviens pas à comprendre pourquoi !
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5$ test_malloc a = 1234567890 Oups! Illegal storage access. $
Je pense que l'erreur dois provenir de la fonction « number_duplicate() », mais je n'en suis pas certain.
Et je ne vois pas comment débogguer ce programme.
Quelqu'un peut-il m'aider ?
Merci.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110 #include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef unsigned short int digit_t; typedef struct number { short sign; int length; digit_t *num; } number_t; number_t * initialize () { number_t *obj; obj = (number_t *) malloc (sizeof (number_t)); if (obj == NULL) { perror ("malloc"); exit (EXIT_FAILURE); } obj-> sign = 1; obj-> length = -1; obj-> num = NULL; return obj; } number_t * number_read (char *str) { number_t *obj = initialize (); char *ptr; int i; if (str[0] == '-') { obj-> sign = -1; ptr = &str[1]; } else if (str[0] == '+') { obj-> sign = 1; ptr = &str[1]; } else { obj-> sign = 1; ptr = &str[0]; } obj-> length = strlen (ptr); obj-> num = (digit_t *) malloc (obj-> length * sizeof (digit_t)); if (obj-> num == NULL) { perror ("malloc"); exit (EXIT_FAILURE); } for (i = 0; i < obj-> length; i++) { obj-> num[i] = ptr[obj-> length - i - 1] - '0'; } return obj; } void number_write (char *name, number_t *this) { int i; printf ("%s = ", name); if (this-> sign < 0) printf ("-"); for (i = this-> length; i > 0; i--) printf ("%d", this-> num[i - 1]); printf ("\n"); } number_t * number_duplicate (number_t *this) { number_t *obj; memcpy (obj, this, sizeof (this)); return obj; } void catch (int signal_id) { printf ("Oups! Illegal storage access.\n"); exit (EXIT_FAILURE); } int main (void) { char *str_a = "1234567890"; number_t *a; number_t *b; signal (SIGSEGV, catch); a = number_read (str_a); number_write ("a", a); b = number_duplicate (a); number_write ("b", b); exit (0); }
Partager