Am I allocating enough memory correctly?

In my options.h
1
2
3
4
const int MAX_OPTIONS = 75;
struct Options {
	char *firstNames[MAX_OPTIONS];
};


In my options.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "options.h"
struct Options *opt = NULL;

void initilizeOptions (void)
{
	do
	{
		if ((1) * sizeof(struct Options) <= 0)
			perror("calloc failure");
		if (!((opt) = (struct Options *) calloc ((1), sizeof(struct Options))))
		{ 
			perror("calloc failure");
			abort();
		}
	} while(0);
	
	opt->firstNames[0] = _strdup("Adam");
	opt->firstNames[1] = _strdup("David");
	opt->firstNames[2] = _strdup("Michael");
	opt->firstNames[3] = _strdup("Johnathan");
}


In my test.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "options.h"
extern struct Options *opt;

void test(void)
{
	initilizeOptions();
	printf("%s\r\n", opt->firstNames[0]);
	printf("%s\r\n", opt->firstNames[1]);
	printf("%s\r\n", opt->firstNames[2]);
	printf("%s\r\n", opt->firstNames[3]);

	/*
	Prints:
	 Adam
	 David
	 Michael
	 Johnathan
	*/
}

test();


MY QUESTION:

Am I calloc'ing correctly? The way in which I'm doing this, is it reserving enough memory for the first names? I'm confused on how I am allocating enough memory for, let's say "Adam" as I am if it were "Rumplestiltskin".

Thanks for viewing and look forward for thoughts and advice.
Last edited on
Taking a second look, would I be correct to assume that by using _strdup() as I am, memory allocation in this instance is okay?

I'm assuming that this is good:
1
2
3
4
opt->firstNames[0] = _strdup("Adam");
opt->firstNames[1] = _strdup("David");
opt->firstNames[2] = _strdup("Michael");
opt->firstNames[3] = _strdup("Johnathan");


But this is bad:
1
2
3
4
opt->firstNames[0] = "Adam";
opt->firstNames[1] = "David";
opt->firstNames[2] = "Michael";
opt->firstNames[3] = "Johnathan";


Agreed?
thats right.

don't forget to free the memory allocated by strdup.
Your program should not link. There is no global opt variable defined. The one defined in initilizeOptions is local and stops existing when the function returns (leaking all memory allocated therein.)

Btw, it's "initialize."
Last edited on
Your program should not link. There is no global opt variable defined. The one defined in initilizeOptions is local and stops existing when the function returns (leaking all memory allocated therein.)


Made a slight mistake in the code. I had put struct Options *opt = NULL; inside the function when in reality it's not. (I edited the post to show correctly).

Yes, everything works fine, I was mainly concerned if I was allocating memory correctly. Thanks all for the replies!
Topic archived. No new replies allowed.