Search code examples
cmallocdynamic-arrayscharacter-arrays

Will successive calls to malloc allocate space directly after the previous call in c?


I am talking about using char* and dynamic arrays. Specifically I want to use a 2d array to break up a line of commands and options into their components

For example:

char *dynamicArr = malloc(1 * sizeof(char));//allocate first letter
int i = 0;
while(string[i] != '\0'){
    dynamicArr[i] = string[i];
    //would I be able to allocate more memory onto the end of dynamicArr here?
}

Obviously I could just use strlen and strcpy in this case, but I am trying to parse a line of commands using various tokens, ' ' '\"' and '\''. So the individual strings are not null terminated. I have written it using Static 2d arrays but I want to make it dynamic so that it can handle commands of any size.


Solution

  • Will successive calls to malloc allocate space directly after the previous call in c?

    No. Not necessary. malloc allocates contiguous chunk of memory but it doesn't guarantee that the next call to malloc will allocate the chunk just after the previous one.

    I have written it using Static 2d arrays but I want to make it dynamic so that it can handle commands of any size.

    Use realloc() function.