char **res = (char **)malloc(sizeof(char *) * 1) at this line i have used {sizeof(char *) * 1} but i have placed more than one string with different length. I dont get how is this working, or is it just my compiler not showing error/warning or is this correct.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
char **res = (char **)malloc(sizeof(char *) * 1);
res[0] = "mang0000000o";
res[1] = "tango00000";
res[2] = "lango";
res[3] = "django";
for (int x = 0; x < 4; x ) {
puts(res[x]);
putchar('\n');
}
return 0;
}
CodePudding user response:
In this case, you have allocated memory for an array of pointers of length 1. And when you turned to an element that you didn't allocate memory for, you just turned to the next piece of memory after the first element of the arrays. If you try to do this in a cycle of at least a hundred elements, you are almost guaranteed to get a segmentation fault. The error does not occur when you access memory that you have not allocated, but when you access memory already occupied by someone.
In such cases, you should allocate memory for sizeof(char *) * (n 1) where n is the number of elements you need. You will write NULL to the last pointer, so that it can be conveniently iterated through while or for.
CodePudding user response:
This should work:
#include<stdio.h>
#include<stdlib.h>
int main() {
const char **res = malloc(4 * sizeof *res); // Buff the size up a little bit
res[0] = "mang0000000o";
res[1] = "tango00000";
res[2] = "lango";
res[3] = "django";
for (int x = 0; x < 4; x ) {
puts(res[x]);
putchar('\n'); // Note that 'puts' automatically adds a newline character '\n'
}
free(res);
return 0;
}
Also note that you don't necessarily need the string.h
header.
Hope this worked out for you.