Pregunta

I am trying to just allocate memory to char pointer (its supposed to store hex values later) As soon as i run this code the program crashes. (I have to use C-String)

int main() {
    char *c = (char*)malloc(sizeof(unsigned int)*2);
}

I see this all over the internet as example, but it fails on my machine. Why?

¿Fue útil?

Solución

Okay the solution was as easy as the question was supposed to be... I did not see that the .exe file could not be generated and I was therefore running an old .exe file compiled 1hour ago...

Otros consejos

Malloc is C, you're trying to do C++.

I would simply do this:

char *c;
c=new char[Max_Size];

Obviously Max_Size would be the size of your intended array.

Try this:

#include <stdlib.h> // for malloc
#include <stdio.h>

int main() {
    char *c = (char*)malloc(sizeof(unsigned int)*2); //It's work

    printf("%d",sizeof(c));

    return 0; // required
}

You did not say what you mean saying that it fails. In any case you have to include header <stdlib.h>

if the program is written in C or <cstdlib> if the program is written in C++.

C code:

#include <stdlib.h>

int main() {
    char *c = (char*)malloc(sizeof(unsigned int)*2);
    free( c );
}

And in any case you should present a code that allows to reproduce the situation. I think that the problem is not in this code but somewhere else where you overwrite memory. The code you showed I think is irrelevant.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top