'Making a pattern using dynamic memory allocation
I was trying to make a pattern using pointers and DMA in C. I want the user to enter a number and then print some pattern and this patterns lengt will be equal to the entered number. While I was tinkering with my code I had some issues. More explanation down below the code.
This is my code:
#include <stdio.h>
#include <stdlib.h>
void makepattern(int lenght);
int main()
{
int deger;
scanf("%d", °er);
makepattern(deger);
return 0;
}
void makepattern(int lenght)
{
int max = (2*lenght) - 1;
char *p = (char *) malloc(lenght * sizeof(char));
int middle = lenght - 1;
int counter = 0;
for(int i = 0; i < lenght; i++)
{
counter += 1;
for(int a = 0; counter > a; a++)
{
*(p + middle + a) = '*';
*(p + middle - a) = '*';
}
for(int b = 0; b < max; b++)
{
if(*(p + b) == '*')
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
free(p);
}
the pattern should be something like this:

Everthing was fine until I tried 18. How can this happen? My code just worked fine with numbers 17 or below. But it started acting strange after 17.
Here are some images.


Solution 1:[1]
@WhozCraig's answer is correct. I was trying to write an adress which was not allocated beforehand and this caused undefined behavior.
Problem solved by just changing
char *p = (char *) malloc(lenght * sizeof(char));
to
char *p = (char *) malloc(max * sizeof(char));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Burant |
