PDA

View Full Version : running c program in Terminal




rmumma2
Mar 15, 2008, 04:26 PM
Hello everyone,

I have just installed x code tools and compiled a c program
it compiled successfully , but when i try to run it by using ./a.out it is giving Bus error.

Please help me out here.

Regards
Rahul



aaronw1986
Mar 15, 2008, 04:34 PM
Could we maybe see some code?

rmumma2
Mar 15, 2008, 04:36 PM
the code

#include <stdio.h>

int main()
{
char *p="Hello world";
int i;
for(i=0;i< 10;i++)
*(p+i)='$';
printf("%s",p);
return (1);
}

Eraserhead
Mar 15, 2008, 04:39 PM
In future please use and blocks for code :). Also for clarity can you add { and } to the for loop.

toddburch
Mar 15, 2008, 05:05 PM
You've defined a constant of "Hello world!" and set p to point to it. So far, so good.

However, you then try to modify the constant, and your compiler has most likely marked the constant to be loaded into protected storage. Thus, the bus error when you attempt to modify read-only stack storage.

Rework your program to either malloc() storage from the heap and copy your constant into it, or, allocate a char array in the stack and copy your constant into that, then modify it.

Todd

rmumma2
Mar 15, 2008, 06:28 PM
Thanks Todd for the reply
and eraserhead I sure will follow ur intstructions from next time onwards

lee1210
Mar 15, 2008, 06:53 PM
You've defined a constant of "Hello world!" and set p to point to it. So far, so good.

However, you then try to modify the constant, and your compiler has most likely marked the constant to be loaded into protected storage. Thus, the bus error when you attempt to modify read-only stack storage.

Rework your program to either malloc() storage from the heap and copy your constant into it, or, allocate a char array in the stack and copy your constant into that, then modify it.

Todd

Todd was pretty clear, but I felt like implementing this:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main(int argc, char **argv) {
char *p="Hello World";
int i,end;
char *copy_p = NULL;
printf("Before copy: %s\n",p);
copy_p=(char *)malloc((size_t)(strlen(p) + 1));
if(!copy_p) { //Hopefully the system can allocate 12 bytes, but for safety...
fprintf(stderr,"Could not allocate memory for copy_p, errno: %d\n",errno);
return 0;
}
strcpy(copy_p,p); //Only reason not to use strncpy is we just allocated
printf("After copy, before replace: %s\n",copy_p);
end=strlen(copy_p); //What is the length of the string literal changes?
for(i=0;i<end;i++) { //I just replaced the whole string. Your example would leave $$$$$$$$$$d\0 in the buffer, not sure what the intent was
copy_p[i] = '$'; //Let the compiler do the pointer arithmatic
}
printf("After replace: %s\n",copy_p);
return 1;
}