Allocating memory for a string in C using malloc

10,992

Solution 1

The problem is right here:

char* memory = (char*)malloc(sizeof(char)*strlen(string));
memory = string; <<<
strings[i] = memory;

You will lose memory if you assign strings to pointers like this.

Either:

a) Copy the string into the newly allocated memory using strcpy() or strncpy(), also make sure you have enough space for the NULL character \0

strings[i] = (char*)malloc(sizeof(char) * (strlen(string) + 1));
strcpy(strings[i], string);

b) Use strdup(), which is like a mix between strcpy() and malloc(), it creates just enough space for your string and copies it into a new memory location

 strings[i] = strdup(string);

Solution 2

At least you have to replace

char* memory= (char*)malloc(sizeof(char)*strlen(string));
if (memory == NULL)
    return false;
memory = string;
strings[i] = memory;

by

strings[i] = strdup(string)

Note that using scanf("%s", string) the separator between the read string is the space

Share:
10,992

Related videos on Youtube

איתן לוי
Author by

איתן לוי

Updated on June 04, 2022

Comments

  • איתן לוי
    איתן לוי almost 2 years

    I am trying to allocate memory for an array of strings using malloc. The size of each string is not known before the input from the user, so this is how I tried to allocate memory for each element in the array.

    I have some errors with the code, but can't figure them out or can't understand them. I am getting an error regarding the allocation. Can anyone tell me what's wrong about this?

    bool read_strings(char * strings[], int n) 
    {
        int i = 0;
        while (i<n)
        {
            char string[MAX_LENGTH];
            if (scanf("%s", string)!=1)
                return false;
            char* memory= (char*)malloc(sizeof(char)*strlen(string));
            if (memory == NULL)
                return false;
            memory = string;
            strings[i] = memory;
            i++;
        }
        return true;
    }
    

    Thanks a lot!

    • lurker
      lurker over 5 years
      memory = string; here you just overwrote (lost) your allocated memory pointer.
    • yyny
      yyny over 5 years
      you're looking to do a strcpy.
    • איתן לוי
      איתן לוי over 5 years
      Why? And how do I fix it?
    • bruno
      bruno over 5 years
      better look at strdup
    • bruno
      bruno over 5 years
      warning scanf will stop at the first space, it is not a readline
    • איתן לוי
      איתן לוי over 5 years
      I am not familiar with those functions, therefore I am not allowed to use them.
    • bruno
      bruno over 5 years
      what is the separator between the strings ?
    • lurker
      lurker over 5 years
      memory is a variable that holds your new pointer. memory = string assigns the value of string to memory. What was in memory before that is now gone. You need to use the string function library to copy a string when you have the pointers to the strings. It is the standard way to copy/move strings around. If you can't use them, then you'll need to write your own strcpy. You can find source for it on the interwebs.
    • Neil
      Neil over 5 years
      Like a database, if you have a MAX_LENGTH, consider just statically allocating MAX_LENGTH+1 chars and have wasted space when the strings are shorter. (You may not want this if MAX_LENGTH is large.)
  • ruirodrigues1971__
    ruirodrigues1971__ over 5 years
    @lurker it was copy-past mistake... I saw your warning after I correct the error. Thanks anyway
  • ruirodrigues1971__
    ruirodrigues1971__ over 5 years
    I like your answer. Maybe to be more perfect strings[i] = strndup(string, MAX_LENGTH);
  • bruno
    bruno over 5 years
    @ruirodrigues1971 The problem is not the strdup, it is the scanf without limitation
  • kiran Biradar
    kiran Biradar over 5 years
    You cannot assign strings to pointers in such a manner. well you can..
  • Matija Novosel
    Matija Novosel over 5 years
    But with OPs code, he will lose memory. Just thought it was best practice.
  • kiran Biradar
    kiran Biradar over 5 years
    But your statement was very absurd and misleading as you forgot add why he should not assign like that.
  • Neil
    Neil over 5 years
    strdup is a POSIX function and not part of the C standard; it may not be implemented in certain OSs, (but it is easy to duplicate.)