Memory Allocation Questions
Memory Allocation Questions
Memory Allocation
A: The pointer variable answer has not been set to point to any valid
storage. The simplest way to correct this fragment is to use a local array,
instead of a pointer.
7.2: I can't get strcat() to work. I tried "char *s3 = strcat(s1, s2);" but I
got strange results.
A: Again, the main problem here is that space for the concatenated result is
not properly allocated.
7.3: But the man page for strcat() says that it takes two char *'s as
arguments. How am I supposed to know to allocate things?
7.3b: I just tried the code "char *p; strcpy(p, "abc");" and it worked. Why
didn't it crash?
A: Only enough memory to hold the pointer itself, not any memory for the
pointer to point to.
A: Make sure that the pointed-to memory is properly (i.e. not locally)
allocated.
7.7: Why does some code carefully cast the values returned by malloc to the
pointer type being allocated?
7.8: Why does so much code leave out the multiplication by sizeof(char) when
allocating strings?
malloc'ed memory until the program tries to use it. Is this legal?
7.16: I'm allocating a large array for some numeric work, but malloc() is
acting strangely.
A: Make sure the number you're trying to pass to malloc() isn't bigger than a
size_t can hold.
7.17: I've got 8 meg of memory in my PC. Why can I only seem to malloc 640K
or so?
A: Make sure you aren't using more memory than you malloc'ed, especially for
strings (which need strlen(str) + 1 bytes).
7.20: You can't use dynamically-allocated memory after you free it, can you?
A: No. Some early documentation implied otherwise, but the claim is no longer
valid.
7.22: When I call malloc() to allocate memory for a local pointer, do I have
to explicitly free() it?
A: Yes.
7.25: Why doesn't my program's memory usage go down when I free memory?
as it is allocated.
7.27: So can I query the malloc package to find out how big an allocated
block is?
A: Not portably.
A: calloc() takes two arguments, and initializes the allocated memory to all-
bits-0.
8.2: Why won't the test if(string == "value") correctly compare string
against the value?
A: In C, if you have the character, you have 8.9: Why is sizeof('a') not 1?
A: Character constants in C are of type int.