Kayo Hisatomi <[EMAIL PROTECTED]> wrote: Hi Nico,
>> As far as I know this is not necessarily correct. It might well happen >> that the string " bye 1 " is stored in a read-only part of memory >> during process initialisation. I thought on this too, but I could not think in another area than the .text section... This is a good question: are the static strings allocated in the .text area? Regards, Kayo. ----- Original Message ---- From: Nico Heinze To: [email protected] Sent: Wednesday, April 11, 2007 2:15:11 PM Subject: [c-prog] Re: Segmentation fault in a simple function. --- In [email protected], Kayo Hisatomi wrote: > > Hi Roberto, > > The problem is in this line in the main() function: > char *s0 = " bye 1 "; > > You are not allocating memory for the string, but just for > the pointer. So, try this: > char s0[] = " bye 1 "; > > And the program will work. > > Regards, > Kayo. As far as I know this is not necessarily correct. It might well happen that the string " bye 1 " is stored in a read-only part of memory during process initialisation. A better way to perform the ltrim() operation is to allocate some memory within the ltrim() function dynamically, namely just as much as is needed to store the trimmed string (plus trailing '\0' byte). However, this of course has the disadvantage that this piece of memory has to be deallocated later on, e.g. using delete[] or free(). On the other hand this has the advantage that you will never mess around with memory belonging to some other part of your application; in your ltrim() function you change the memory that the parameter points to, and this is really bad practice. Regards, Nico Hi, I think strings are stored in .text See this output of strings on the executable ===== [EMAIL PROTECTED]:~/tech/code/trim$ strings trimm /lib/ld-linux.so.2 __gmon_start__ libc.so.6 strcpy printf strerror puts calloc __errno_location exit _IO_stdin_used __libc_start_main free GLIBC_2.0 PTRh [^_] ltrim() : [%p] [%s], len: %d buffer before the filling: [%p] [%s] [%d] buffer after the filling with the string: [%p] [%s] [%d] p: %d, c: [%c] 0X%2X reset string [%p], len: %d to 0 prepare the return parameter new string: [%s] l: %d -> free memory : [%p] [%s] [%d] memory freed ltrim() : (trimmed) [%s], len: %d ltrim() : cannot allocate memory [%s] return the value before: [%s] after [%s] bye 1 ===== if optimized for size (gcc -Os) , the strings appear in .rodata section else they appear in .text section. --------------------------------- Don't be flakey. Get Yahoo! Mail for Mobile and always stay connected to friends. [Non-text portions of this message have been removed]
