In my program you have to create a duplicate function that receives a string and returns a pointer to a new string that is the copy of the previous one. My program "works" the problem is that if the initial string passed as an argument to my duplicate function I define it dynamically, when I release that memory my "copy" string disappears and the compile throws many errors and I do not understand why. since if it would not be easier to do directly p = v; and ready.
I leave the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char*duplicar(char*);
main()
{
char *p,*v;
v=(char*)malloc(4*sizeof(char));
v="sip";
p=duplicar(v);
free(v); //con el free no funciona ?poque¿
printf("%s\n",p);
return 0;
}
char*duplicar(char*v)
{
int l,i;
char *k;
l=strlen(v);
if(l==0)
{
k=NULL;
}
k=(char*)malloc(l*sizeof(char)); //si malloc falla retorna NULL
for(i=0;i<l;i++)
{
*(k+i)=*(v+i);
}
return k;
}
I leave the error returned by the compiler
* Error in './ej14': double free or corruption (! prev): 0x08048600 * ======= Backtrace: ========= /lib/i386-linux-gnu/libc.so.6[0x4a5f871b] /lib/i386-linux-gnu/libc.so.6[0x4a5f9460] ./ej14[0x80484f9] /lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x4a59c5b5] ./ej14[0x80483e1] ======= Memory map: ======== 08048000-08049000 r-xp 00000000 00: 0e 10148 / home / knoppix / ej14 08049000-0804a000 rw-p 00000000 00: 0e 10148 / home / knoppix / ej14 0804a000-0806b000 rw-p 00000000 00:00 0 [heap] 4a560000-4a57f000 r-xp 00000000 00: 0e 25 /UNIONFS/lib/i386-linux-gnu/ld-2.17.so 4a57f000-4a580000 r - p 0001f000 00: 0e 25 /UNIONFS/lib/i386-linux-gnu/ld-2.17.so 4a580000-4a581000 rw-p 00020000 00: 0e 25 /UNIONFS/lib/i386-linux-gnu/ld-2.17.so 4a583000-4a6f1000 r-xp 00000000 00: 0e 30 /UNIONFS/lib/i386-linux-gnu/libc-2.17.so 4a6f1000-4a6f2000 --- p 0016e000 00: 0e 30 /UNIONFS/lib/i386-linux-gnu/libc-2.17.so 4a6f2000-4a6f4000 r - p 0016e000 00: 0e 30 /UNIONFS/lib/i386-linux-gnu/libc-2.17.so 4a6f4000-4a6f5000 rw-p 00170000 00: 0e 30 /UNIONFS/lib/i386-linux-gnu/libc-2.17.so 4a6f5000-4a6f8000 rw-p 00000000 00:00 0 4b848000-4b864000 r-xp 00000000 00: 0e 8031 /UNIONFS/lib/i386-linux-gnu/libgcc_s.so.1 4b864000-4b865000 rw-p 0001b000 00: 0e 8031 /UNIONFS/lib/i386-linux-gnu/libgcc_s.so.1 b774e000-b774f000 rw-p 00000000 00:00 0 b7760000-b7763000 rw-p 00000000 00:00 0 bfefd000-bff1e000 rw-p 00000000 00:00 0 [stack] ffffe000-fffff000 r-xp 00000000 00:00 0 [vdso] Aborted