2

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; } 
1
  • memset(tab,'X',n*sizeof(tab)); --> memset(tab,'X',n*sizeof(*tab)); Commented Jan 17, 2016 at 23:17

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks that did the trick :D but it's weird because I take the sintax for memset from a book and it is like this: memset(target, NULL, sizeof(target));
. Your book is not really clear. Instead of sizeof(target) think length. I invite you to read the man page about that it is clean. In your case n * sizeof(char) because your tab contain a certain number of char
In this case you can also use sizeof *tab
2

The C library function void *memset(void *str, int c, size_t n) copies the character c (an unsigned char) to the first n characters of the string pointed to, by the argument str.

memset(tab,'X',n*sizeof(char)); 

You've written n*sizeof(tab), you are copying the character X to unknown memory which might cause crash during runtime.

Comments

2

Look into this line:

memset(tab,'X',n*sizeof(tab)); 

You declared tab as a pointer, and a storage size of a pointer is more than one byte. Multiplying that by n which is the size of the array you want will cause you to copy data to memory space you're not allowed to access which is why you get a segmentation fault.

If you must use sizeof, then do this:

memset(tab,'X',n*sizeof(char)); 

or better yet, just do this:

memset(tab,'X',n); 

because a char is one byte and n times 1 = n.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.