-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_storage.c
68 lines (53 loc) · 1.41 KB
/
string_storage.c
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
#include<stdio.h>
char * getString(){
char *str = "Hello";
/* Segmentation fault as string is stored in
* read-only memory and thus we're trying to modify
* read-only memory.
*/
// str[0] = 'W';
printf("getString: %s\n", str);
/* String is returned without issues as the memory is
* allocated at run-time mostly in a read-only block
* (generally in data segment) that is shared among
* functions.
*/
return str;
}
char * getStringArray(){
char str[] = {'H', 'e', 'l' ,'l', 'o', '\0'};
/* No segmentation fault as the string is an array which
* is present only locally.
*/
str[0] = 'W';
printf("getStringArray: %s\n", str);
/* String is not returned correctly as it is present in
* local storage and may not be present after function
* returns.
* This even gives a compiler warning,
*
* warning: function returns address of local variable [-Wreturn-local-addr]
* return str;
* ^~~
*/
return str;
}
char * getStringArrayCast(){
char *str = (char [6]){'H', 'e', 'l' ,'l', 'o'};
/* No segmentation fault possibly as the string is an array in
* local storage.
*/
str[0] = 'W';
printf("getStringArrayCast: %s\n", str);
/* Value returned is grabage.
* Reason is not so clear yet.
* Maybe, "Casting is evil"
*/
return str;
}
int main(void) {
printf("%s\n",getString() );
// printf("%s\n",getStringArray() );
printf("%s\n",getStringArrayCast() );
return 0;
}