Question:
C programming segmentation fault?
dudemeister88
2009-11-08 04:32:24 UTC
I have a really simple program that I am sure should be working. I am trying to assign characters to an array, but it keeps coming up with segmentation fault!!

int main(void){

int size;
char *para;

size = sizeof(char);
para = (char*)malloc(4*size);

para[0] = 'a';
para[1] = 'b';
para[2] = 'c';
para[3] = 'd';

printf("\npara[0] = %s\n",para[0]);

return EXIT_SUCCESS;

}

Anyway, I know this is basic but I am overseeing the solution. At least it means some easy points for someone by answering it :D. Thanks in advance to those who help.
Four answers:
nivik
2009-11-08 04:47:51 UTC
In the printf function, use "%c" instead of "%s" because you are outputting a character and not a string.
Stephanie
2009-11-08 08:19:28 UTC
Segmentation fault implies you've done something wrong with your memory management. Are you using Linux (or similar)? I think you are, as you refer to it as a segmentation fault. If so, look at using Valgrind, which will highlight which lines are causing strange behaviour, if you compile with -g in gcc, then execute your program with:

$ valgrind ./programname



It looks like your code should be fine (once you've swapped the %s with %c) so I am curious to know as to why this would happen.



one thing you might want to watch out for is that 'size' as you have defined it is an int, whereas sizeof() returns a size_t (although this shouldn't matter), and in C (contrary to C++), you don't need to cast the return of malloc.



the answer above about the nul-terminated string will cause problems as it writes past the end of para (4th index), and it shouldn't be necessary as you are using it as an array, not a string.
2009-11-08 07:10:00 UTC
Hm....



















U must set terminate null string at end of array.

para[4] = 0;
paulo
2016-10-16 06:48:49 UTC
Your argv argument statement could desire to be char **argv or char *argv[] somewhat than char *argv. In different words: int significant (int argc, char **argv){ //Parameter examine if (argc < 2){ printf("incorrect form of enter parameters.nUsage %s report", argv[0]); return EXIT_SUCCESS; } return EXIT_SUCCESS; }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...