Click to See Complete Forum and Search --> : Initializing strings (kind of) and setting them... in C


azambuja
02-19-2006, 10:34 PM
Hey guys...
First of I'll acknowledge that this question doesn't have much merrit because of the lack of info I have... sorry

Here it is: why would it be acceptable/unacceptable to do this:

char *buf, *gbuf;
int i;
buf=strdup(buf,"goto:/home");
for(i=0;i<(strlen(buf)-5);i++) gbuf[i]=buf[i+5] ; gbuf[i]='\0';
printf("final: %s\n",gbuf);


I can do it in a simple .c program by itself but when I'm trying to change a certain program (enlightenment dr17's efm, if you must know) where it looks to me like it's exactly the same thing it segfaults at the for loop... any possible suggestions of why?

EDIT: doh, I forgot to mention, in the other program when I change *gbuf to gbuf[4096], it works, that's what's driving me mad

NOTE: yes I am a n00b.

Thanks for your time.

truls
02-20-2006, 01:22 AM
It crashes because you have not allocated any memory for gbuf. If you try to add:
gbuf = malloc(4096);
It will work exactly as if you were using gbuf[4096].

The reason that you don't need to allocate memory for dup, is that strdup() does this for you. Try looking at the manual pages for strdup (man 3 strdup).

azambuja
02-20-2006, 02:50 AM
It crashes because you have not allocated any memory for gbuf. If you try to add:
gbuf = malloc(4096);
It will work exactly as if you were using gbuf[4096].

The reason that you don't need to allocate memory for dup, is that strdup() does this for you. Try looking at the manual pages for strdup (man 3 strdup).

Hey thanks for answering... and yeah I get all that, what does not make sense to me, though, is that if I put the code on my 1st post on a program by itself (without gbuf[4096] or malloc) it works... and I don't understand why...

maybe I'll just forget about it...

Thanks anyways!

bwkaz
02-20-2006, 07:54 PM
It might not segfault, but it definitely does not work right. You are still clobbering memory somewhere that shouldn't be clobbered. (The exact addresses that you clobber will depend on the random values on the stack in the position that your gbuf pointer is located.)

You are making it less likely to clobber something important (or writing to an unallocated address, which is what causes a segfault) by making your program short, and making the string short as well. But it's still wrong.

azambuja
02-20-2006, 11:03 PM
Ohhh.... thanks... I guess that makes a lot of sense... thanks bwkaz...