Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to Allocate memory for a name in C?

+3 votes
asked Mar 29 by Bruno Arnauth (180 points)

2 Answers

+1 vote
answered Apr 1 by Peter Minarik (88,130 points)
edited Apr 11 by Peter Minarik
 
Best answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME_LENGTH 32

int main()
{
    char * name = (char *)(malloc(sizeof(char) * MAX_NAME_LENGTH));
    strcpy(name, "John Doe");
    printf("Hello, %s!\n", name);
    free(name);

    return 0;
}
  1. First, you allocate the memory with malloc(). Since it returns you a void *, you need to cast it to the right type (char * in our example).
  2. Then, you fill that memory with value. You absolutely cannot do name = "John Doe", because you'll loose track of your allocated memory (causing a memory leak) and later, when you'll try to free the memory, now it points to a location that was not allocated by you and thus, you must not deallocate it. So use strcpy() to fill the memory with string data.
  3. Then you use your variable (we simply print it in the example).
  4. Finally, you need to release the allocated memory with free().

I hope this gives you a good idea of how to deal with dynamic memory de/allocation in your C program.

Good luck!

0 votes
answered Mar 30 by Mayur Gaikwad (250 points)
by using calloc and malloc you can do so.
commented Apr 9 by hariom patel (100 points)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
    char *name;
    name = (char *)malloc(50 * sizeof(char));
    if (name == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }
    printf("Enter your name: ");
    fgets(name, 50, stdin);
    size_t len = strlen(name);
    if (len > 0 && name[len - 1] == '\n') {
        name[len - 1] = '\0';
    }
    printf("Hello, %s!\n", name);
    free(name);

    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...