Yes, it's a matter of style, because you'd expect sizeof(char) to always be one.

On the other hand, it's very much an idiom to use sizeof(foo) when doing a malloc, and most importantly it makes the code self documenting.

Also better for maintenance, perhaps. If you were switching from char to wchar, you'd switch to

Copywchar *p = malloc( sizeof(wchar) * ( len + 1 ) );

without much thought. Whereas converting the statement char *p = malloc( len + 1 ); would require more thought. It's all about reducing mental overhead.

And as @Nyan suggests in a comment, you could also do

Copytype *p = malloc( sizeof(*p) * ( len + 1 ) );

for zero-terminated strings and

Copytype *p = malloc( sizeof(*p) * len ) );

for ordinary buffers.

Answer from brainjam on Stack Overflow
🌐
George Washington University
www2.seas.gwu.edu › ~simhaweb › C › modules › module3 › module3.html
Module 3: Pointers, strings, arrays, malloc
p = (int*) malloc (sizeof(int)); An easy way to remember this is: "the cast type is the same as the argument to ... It looks more complicated with 2D arrays, as we will see, but the essence is the same. After the pointer has a value, we can actually print the address: #include <stdio.h> #include ...
🌐
Wikibooks
en.wikibooks.org › wiki › A_Little_C_Primer › C_Dynamic_Memory_Allocation_&_Deallocation
A Little C Primer/C Dynamic Memory Allocation & Deallocation - Wikibooks, open books for an open world
September 10, 2008 - For example, let's use "malloc()" to allocate an array of "char": /*malloc.c */ #include <stdio.h> #include <stdlib.h> /*For "malloc", "exit" functions. */ int main() { char *p; /*Pointer to array. */ unsigned count; /*Size of array. */ puts( "Size of array?"
Discussions

[C] Storing strings using an array of char pointers and malloc.
The malloc function allocates a block of memory of a specified size, and then returns a pointer to the first memory address of that block. If you are using malloc to allocate memory for a string, you will treat this block of memory as an array of chars, so the pointer to the first memory address in the block will be a pointer to a char (the first one). More on reddit.com
🌐 r/learnprogramming
20
5
July 29, 2013
How to allocate array of pointers for strings by malloc in C? - Stack Overflow
No. I have pointer new_message with array of pointers of strings. I need allocate char array for thirty adress strings by malloc. I dont know how to allocate new_array for copy adress of strings... More on stackoverflow.com
🌐 stackoverflow.com
May 6, 2017
c - When to use malloc for char pointers - Stack Overflow
malloc for single chars or integers and calloc for dynamic arrays. ie pointer = ((int *)malloc(sizeof(int)) == NULL), you can do arithmetic within the brackets of malloc but you shouldnt because you should use calloc which has the definition of void calloc(count, size)which means how many items ... More on stackoverflow.com
🌐 stackoverflow.com
c - Initialize an array of char pointers with malloc - Stack Overflow
It is not necessary to malloc storage for this array; it is embedded in struct List. Thus, the first call to malloc is unnecessary, as is the check immediately afterward. The call to malloc inside the loop, and check after, are correct. Also, in C, do not cast the return value of malloc; it can actually hide bugs. Also also, sizeof(char... More on stackoverflow.com
🌐 stackoverflow.com
July 11, 2013
🌐
Reddit
reddit.com › r/learnprogramming › [c] storing strings using an array of char pointers and malloc.
r/learnprogramming on Reddit: [C] Storing strings using an array of char pointers and malloc.
July 29, 2013 -

I've been given the task of reading words into an array and then running insertion sort on them. The way it has been set out to do this is by using an array of char pointers and then assigning memory to each index in order to store a string. The code for that is already in place. But I just don't understand how using malloc makes space for a sting within a char? I'm honestly not even sure if what I just wrote makes sense. Pointers are frying my brain. Any help would be much appreciated. I've done a fair bit of Java before if that helps any explaination .

🌐
Quora
quora.com › How-do-I-dynamically-allocate-a-char-array-using-a-malloc-function-in-C
How to dynamically allocate a char array using a malloc function in C - Quora
Answer (1 of 5): Dynamic memory allocation is quite a useful concept in C language. In order to allocate memory dynamically using C language the following code will be enough: char *s = (char *)malloc(20 * sizeof(char)); The above line allocates memory for storing 20 characters or in fact 19 ch...
Find elsewhere
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 155504-using-malloc-array-character-pointers.html
using malloc for an array of character pointers
March 30, 2013 - items_ptr = (char *) malloc Do not cast malloc or, if you do, make sure it's cast to the same type as the variable you're assigning to. Yes, I read the reply.
🌐
Medium
csnotes.medium.com › malloc-in-c-for-int-and-char-c3677b857b65
Malloc in C, for int * and char * | by zihan | Medium
May 15, 2021 - SIDE NOTE: In C, a string is by definition an array of char null-terminated (which means putting a \0 at the end). This means, that you will need enough chars to write your word, plus 1 char to null-terminate your string . With the brackets notation, the size won’t be modifiable later on. And it doesn’t work when you don’t know the exact size upfront. Last but not least. Malloc is a function of type void *, which means it can be casted to whatever type we need (int *, char *, int **, char **).
🌐
UCI
ics.uci.edu › ~dan › class › 165 › notes › memory.html
Pointers and Memory Allocation
Now the fun begins: how to allocate memory for a pointer-vector array. We get memory with the function · char *malloc( nbytes ); malloc returns a character pointer to a contiguous block of nbytes bytes, or a NULL pointer (NULL is defined in the library package <stdio.h>) if it cannot get the space.
🌐
LabEx
labex.io › tutorials › c-how-to-manage-memory-for-char-types-in-c-510337
How to manage memory for char types in C | LabEx
typedef struct MemoryBlock { void* ptr; size_t size; const char* file; int line; struct MemoryBlock* next; } MemoryBlock; void* debug_malloc(size_t size, const char* file, int line) { void* ptr = malloc(size); // Custom tracking logic return ptr; } #define MALLOC(size) debug_malloc(size, __FILE__, __LINE__) ... typedef struct { int* indices; char* values; size_t size; size_t capacity; } SparseCharArray; SparseCharArray* create_sparse_char_array(size_t initial_capacity) { SparseCharArray* arr = malloc(sizeof(SparseCharArray)); arr->indices = malloc(initial_capacity * sizeof(int)); arr->values = malloc(initial_capacity * sizeof(char)); arr->size = 0; arr->capacity = initial_capacity; return arr; }
Top answer
1 of 1
4

Here are some things that may help you improve your code.

Fix the bug

Once memory is freed, it should not be referenced again. Unfortunately, your code allocates memory and then frees it and then returns a pointer to the freed memory. That's a serious bug! To fix it, simply omit the free within the function and make sure the caller calls free instead. Alternatively, you could avoid all of that by reversing the passed string in place.

Use the required #includes

The code uses strlen which means that it should #include <string.h> and malloc and free which means that it should #include <stdlib.h>. It was not difficult to infer, but it helps reviewers if the code is complete.

Use const where practical

In your revere_string routine, the string passed into the function is not and should not be altered. You should indicate that fact by declaring it like this:

char* reverse_string(const char* string)

Check for NULL pointers

The code must avoid dereferencing a NULL pointer if the call to malloc fails. The only indication that it has failed is if malloc returns NULL; if it does, it would probably make most sense to immediately return that NULL pointer.

Learn to use pointers instead of indexing

Using pointers effectively is an important C programming skill. This code could be made much simpler by doing an in-place reversal of the passed string and by using pointers:

char* reverse_string(char* string) {
    if (string == NULL) 
        return string;
    char *fwd = string;
    char *rev = &string[strlen(string)-1];

    while (rev > fwd) {
        char tmp = *rev;
        *rev-- = *fwd;
        *fwd++ = tmp;
    }
    return string;
}
🌐
Williams College
cs.williams.edu › ~freund › cs010 › notes › lecture05.html
Strings & Introduction to Dynamic Memory Management
If we don't know how big we want the array initially, we could do the following: char *school; ... school = (char *)malloc (strlen ("Williams") + 1); strcpy (school, "Williams"); First we declare a string pointer but do not allocate memory to hold the characters in the string.
🌐
C-pointers
c-pointers.com › malloc_ptr › tp_malloc_ptr › char_tp.html
Malloc char Triple pointer - C Pointers Tutorials
1#include <stdio.h> 2 3// Step 1 : Include stdlib.h 4#include <stdlib.h> 5 6int main(void) 7{ 8 // Step 2 : Define Triple Pointer 9 char ***ptr; 10 11 // Step 3.1 : ptr is a triple pointer and points to array of double pointers 12 ptr = malloc(sizeof(char **)); 13 14 // Step 3.2 : *ptr is a double pointer and points to array of single pointers 15 *ptr = malloc(sizeof(char *)); 16 17 // Step 3.3 : **ptr is a single pointer and points to array of characters 18 **ptr = malloc(sizeof(char)); 19 20 // Step 4 : Assign a value to character 21 ***ptr = 65; 22 23 // Step 5 : Print the value of character 24 printf("***ptr = %d\n", ***ptr); 25 26 // Step 6.1 : Free array of characters 27 free(**ptr); 28 29 // Step 6.2 : Free array of single pointers 30 free(*ptr); 31 32 // Step 6.3 : Free array of double pointers 33 free(ptr); 34 35 return 0; 36}
🌐
Eskimo
eskimo.com › ~scs › cclass › notes › sx11a.html
11.1 Allocating Memory with malloc
Very simply, malloc returns a pointer to n bytes of memory which we can do anything we want to with. If we didn't want to read a line of input into a fixed-size array, we could use malloc, instead. Here's the first step: #include <stdlib.h> char *line; int linelen = 100; line = malloc(linelen); ...
🌐
RIT
se.rit.edu › ~swen-250 › activities › MicroActivities › C › mu_string_malloc › distrib › index.html
C Strings: malloc & free
June 1, 2022 - Also included is the symbolic identifier NULL for the pointer to nothing (like null in Java): #define NULL ((void) 0) Note that NULL is a form of 0, meaning a NULL pointer is false and all other pointer values are true. Space is allocated by calling malloc with the number of bytes needed (for strings this is always one more than the maximum length of the string to be stored): char *pc = malloc(MAXSTR + 1) ; // can hold a string of up to MAXSTR characters.
🌐
Reddit
reddit.com › r/c_programming › freeing a char array
r/C_Programming on Reddit: Freeing a char array
January 24, 2024 -

Hello,

I am just brushing up on pointers in preparation for a C unit I will be doing.

For this script

#include <stdio.h>
#include <stdlib.h>
int main(void) {
char (* ptr)[10] = malloc(sizeof(char) * 10);
for(int i = 0; i < 8; i++) {
(*ptr)[i] = 'h';
}
*ptr[9] = '\0';
//free(ptr);   //-------------THIS LINE
printf("%s\n",*ptr);
return 0;
}

What is the difference between 1. free(*ptr) and 2.free(ptr)?

2. Frees the ARRAY that ptr is pointing to

  1. Frees the first element in the array

Is there any difference?

By the way I know that "printf("%s\n",*ptr);" accesses an invalid pointer.

I just used it to notice the printed strings is different whether I free 1 or 2.

Thanks

🌐
Swarthmore College
cs.swarthmore.edu › ~newhall › unixhelp › C_arrays.html
Arrays in C
A single call to malloc allocates a contiguous chunk of heap space of the passed size. ... // declare a pointer variable to point to allocated heap space int *p_array; double *d_array; // call malloc to allocate that appropriate number of bytes for the array p_array = (int *)malloc(sizeof(int)*50); // allocate 50 ints d_array = (int *)malloc(sizeof(double)*100); // allocate 100 doubles // always CHECK RETURN VALUE of functions and HANDLE ERROR return values // here is one example of handling an unrecoverable malloc error // (other error handling code is removed from this document for readabili