You are not logged in.

#1 2008-03-19 13:13:11

[knap]
Member
Registered: 2007-12-29
Posts: 37

Problems running compiled code

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

#2 2008-03-19 13:48:32

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: Problems running compiled code

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

#3 2008-03-19 13:56:29

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,384
Website

Re: Problems running compiled code

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

#4 2008-03-19 14:47:59

[knap]
Member
Registered: 2007-12-29
Posts: 37

Re: Problems running compiled code

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

#5 2008-03-19 14:53:51

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,384
Website

Re: Problems running compiled code

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

#6 2008-03-19 16:16:09

[knap]
Member
Registered: 2007-12-29
Posts: 37

Re: Problems running compiled code

Ok, understood thanks.

Offline

Board footer

Powered by FluxBB