memory allocation for string in C

hi

in the following code, how the memory is allocated for a1 which holds the values of a2 after cpy function call.

 
#include <stdio.h>
#include <string.h>
 
void cpy(char* d, const char* s){
    while(*d++=*s++);
}
 
main(){
 char* a1;
 char* a2="done";
 cpy(a1,a2);
 printf("\n after cpy, a1 = %s",a1);
}
 
output:
after cpy, a1 = done

It is not.

mute@flo-rida:~$ ./cpy
Segmentation fault

So maybe your compiler was pointing a1 somewhere that happen to be writable, blindlessly overwriting what was there.

1 Like

here's my two cents (or three):

  • either you point a1 to some static buffer - with enough space, as in:
char dest[8];
a1 = dest;
cpy(...)
  • or you call malloc() to get dynamic space, as in:
a1 = malloc(8);
cpy(...)
  • or just use strdup() to replace your cpy(), as in:
a1 = strdup(a2);

HTH

alexandre botao
("comets never dodge")

No memory is allocated to a1, you can use a malloc to allocate memory or use an array as mentioned in above post.

A better way of using malloc would be a1 = malloc(strlen(a2)+1);