1

I am trying to implement a dynamic array to my C stack, however I am a bit confused how char malloc works in such that it inserts garbage data as soon as it is created.

Here is the code used to initialize the array and push elements in.

typedef struct {
  char *array;
  int used;
  int size;
} Array;

void initArray(Array *a, int initialSize) {
  a->array = (char *)malloc(initialSize * sizeof(char)+1);
  a->used = 0;
  a->size = initialSize;
}

void pushArray(Array *a, int element) {
  if (a->used == a->size) {
    a->size +=1;
    a->array = (char *)realloc(a->array, a->size * sizeof(char));
  }
  a->array[a->used++] = element;
}

And here is the main snippet where I initialize and push elements into array

int main()
{
    Array a;
    int i=0;
    initArray(&a,0);
    char choice='a';
    char  exp[100]="";
    printf("Please enter an expression\n");
    scanf("%s",exp);
    for (i=0;i<strlen(exp);i++){

        pushArray(&a,exp[i]);

    }

Initializing array

After running the push function

3 Answers 3

5

Unclear how OP determined "it inserts garbage data". Since ``malloc()` does not initialized the contents of the allocated data, insure data is set as needed.

Viewing field array as string is a problem as array is not null character terminated.

Change loop to <= to also push the '\0'.

for (i=0;i<=strlen(exp);i++){
  pushArray(&a,exp[i]);
}

Alternatively append the null character on each push. Note: little need for * sizeof(char) and casting the return value of *alloc()

void initArray(Array *a, int initialSize) {
  a->array = malloc(initialSize + 1);
  a->used = 0;
  a->size = initialSize;
  a->array[0] = '\0';
}

void pushArray(Array *a, int element) {
  if (a->used == a->size) {
    a->size +=1;
    a->array = realloc(a->array, a->size + 1);
  }
  a->array[a->used++] = element;
  a->array[a->used] = '\0';
}
Sign up to request clarification or add additional context in comments.

Comments

5

malloc() does not "put" garbage in the memory allocated, it just doesn't initialize it to anything, so you get whatever "garbage" is there. You can use either memset() to clear out the memory, of just use calloc(), which does it.

2 Comments

Is there a way to overwrite the contents, like a->array="" ?
no, that is not memory copy, but pointer assignment. If you want the malloced memory to represent a C string, set first element to 0, a->array[0] = '\0';
1

Malloc just gives you a pointer to some place in memory, and it's contents will be whatever was leftover the last time some process used it. If you need to get the contents of the allocated memory initialized, you should use calloc instead of malloc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.