You are not logged in.
Pages: 1
Hello, I'm using ArchLinux X86-64 completely updated.
I'm having problems running this code that I compile with GCC:
#include <stdio.h>
int main(void) {
char *a[10];
char b = '8';
*a[0] = b;
printf("%c\n", b);
printf("%c\n", *a[0]);
return 0;
}
The code compiles fine but gives a "Segmentation fault" when I try to run it, it runs (and compiles) ok in another two boxes where I tested it.
I tried a binary compiled in another box in my arch installation and it runs ok also.
This seems to be a problem with GCC and specifically the line number 8 of the code.
Last edited by [knap] (2008-03-19 13:13:47)
Offline
OK. the line char *a[10]; declares an array of 10 char pointers, but doesn't initialize them. Your array probably looks something like this:
a -------> [ 0x234df | 0x23423ad | 0x0 | 0x102 | ... ]
Each pointer in the array is either uninitialized memory, or all initialized to 0x0 (I can't remember how c/c++ array initialization works atm) - in either case, the pointers are garbage, so when you do *a[0] = b; you're assigning a garbage memory location.
Either initialize your array as char a[some size][10] or properly malloc/new each pointer:
char *a[10];
for (int i=0; i<10; i++) {
a[i] = malloc (sizeof(char));
}
*a[0] = b;
Last edited by Cerebral (2008-03-19 13:55:34)
Offline
I just built this and it worked fine (g++ -o test test.cpp) Outputs two 8's.
Edit: I see Cerebral figured it out.
Last edited by Allan (2008-03-19 13:58:38)
Offline
Cerebral
Your suggestion worked, thanks.
But why does the code work in other computers?
And also, why does this work?
#include <stdio.h>
int main(void) {
char *a;
char b = '8';
*a = b;
printf("%c\n", b);
printf("%c\n", *a);
return 0;
}
Shouldn't I also need to allocate the space for the pointer?
Last edited by [knap] (2008-03-19 14:52:08)
Offline
It works for much the same reason that your first code worked on some computers but not others. Sometimes uninitialized pointers happen to point at "usable" memory. It is a bit of Russian roulette...
Offline
Ok, understood thanks.
Offline
Pages: 1