Search code examples
cmemorymallocmemset

C dynamic allocated array using memset for initialisation


So i've make a program about an char array that is dinamically allocated, the program is not yet finished but i've got some different return values after i run the program, no warnings, no errors in compiler so i don't know why i get this also sometimes the program crashes..

#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(){
int n,i;
char *tab=NULL;
printf("New size of array: ");
scanf("%d",&n);
tab=(char*)malloc(n*sizeof(char));
memset(tab,'X',n*sizeof(tab));
for(i=0;i<n;i++)
    printf("%c",tab[i]);
free(tab);
return 0;
}

Solution

  • In your memset you write n * sizeof(tab), I think you wanted to write : n * sizeof(char)

    You can also add a +1 add the end of your malloc and check the return value, just for security.