This might look really silly, but I don't understand what is happening...
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*
gcc -o test test.c -std=c99 && time ./test
*/
int main(int argc, char **argv)
{
char **s;
s = malloc(10);
s[0] = malloc(100);
s[1] = malloc(100);
s[2] = malloc(100);
s[3] = malloc(100);
s[4] = malloc(100);
s[5] = malloc(100);
s[6] = malloc(100);
s[7] = malloc(100);
s[8] = malloc(100);
s[9] = malloc(100);
strcpy(s[0],"test");
strcpy(s[1],"test");
strcpy(s[2],"test");
strcpy(s[3],"test");
// strcpy(s[4],"test");
printf("%s", s[0]);
return 0;
}
If I uncomment strcpy(s[4],"test");
I get seg fault. If I malloc 149 instead of 10, I get seg fault by copying string to [20] element.
I'm coding with c neraly year and it's my first time when I truly feel dump...
Could someone explain me why this is happening?
EDIT
Ok, my mistake. What about:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*
gcc -o test test.c -std=c99 && time ./test
*/
int main(int argc, char **argv)
{
char **ar = NULL;
ar = malloc(sizeof(**ar) * 10);
for (int i = 0; i < 10; i++)
{
char ic[2];
sprintf(ic, "%d", i);
int l = strlen(ic);
ar[i] = (char*)malloc(sizeof(*ar[i]) * (l + 1));
strcpy(ar[i], ic);
// asprintf(&(ar[i]), "%d", i);
printf("%s\n", ar[0]);
}
return 0;
}
Get output like this:
0
0
0
0
�@
�@
�@
�@
�@
�@