B
bwaichu
Is my understanding of the allocation of these correct?
I used fixed sized allocations for the example below, so I realize
there is some optimization that can be done to those.
I would like to use these in a linked list for something else I am
working on, but I want to make sure my understanding of the concept is
correct.
For example, from the code below string[0][0] would equal 'h' after
the copy, right?
The one area where I am not quite certain about is freeing these.
Another area where I am uncertain is how to keep track of the sizes
of all the allocations.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
int
main(void) {
char **string;
string = malloc(20 * sizeof(char *));
if (string == NULL)
errx(1, "malloc failed");
string[0] = malloc(80 * sizeof(char));
if (string[0] == NULL)
errx(1, "malloc failed");
string[1] = malloc(80 * sizeof(char));
if (string[1] == NULL)
errx(1, "malloc failed");
strlcpy(string[0], "hello", 80);
strlcpy(string[1], "world", 80);
printf("%s %s\n", string[0], string[1]);
free(string[0]);
free(string[1]);
free(string);
exit(EXIT_SUCCESS);
}
I used fixed sized allocations for the example below, so I realize
there is some optimization that can be done to those.
I would like to use these in a linked list for something else I am
working on, but I want to make sure my understanding of the concept is
correct.
For example, from the code below string[0][0] would equal 'h' after
the copy, right?
The one area where I am not quite certain about is freeing these.
Another area where I am uncertain is how to keep track of the sizes
of all the allocations.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
int
main(void) {
char **string;
string = malloc(20 * sizeof(char *));
if (string == NULL)
errx(1, "malloc failed");
string[0] = malloc(80 * sizeof(char));
if (string[0] == NULL)
errx(1, "malloc failed");
string[1] = malloc(80 * sizeof(char));
if (string[1] == NULL)
errx(1, "malloc failed");
strlcpy(string[0], "hello", 80);
strlcpy(string[1], "world", 80);
printf("%s %s\n", string[0], string[1]);
free(string[0]);
free(string[1]);
free(string);
exit(EXIT_SUCCESS);
}