Jump to content
  • Advertisement
Sign in to follow this  
Edge Damodred

Calling malloc() on a pointer pointing to a statically allocated array

This topic is 3736 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Got sort of an interesting question. A test program wants me to change the size of a statically allocated array so it can compare it with another array in another function by using strcmp(). The program passes in a pointer to the array to a function and the test expects to have array modified by removing certain elements from it. Now I've tried calling malloc() on the pointer passed into the function to change the size and to my surprise the program did not crash. The basic setup looks something like this
char str[] ="someword";
char str2[] = "differentword";


void DoSomethingToString(char* string)
{
/*----bunch of stuff happening here-----*/
}

char CompareStuff(char* string1, char* string2)
{
 if(!strcmp(string1,string2))
 {
       return 1;
 }
 else
 {
       return 0;
 }
}


int main()
{
 DoSomethingToString(str);
 if(CompareStuff(str,str2))
 {
      printf("HOORAY!\n");
 }
 else
 {
      printf("FAILURE!\n");
 }
 
 return 0;
}

Now my question is, does calling malloc() on the pointer that that is initially pointing to a statically allocated array have any undefined behavior? Also does this in any way affect the array allocated on the stack?

Share this post


Link to post
Share on other sites
Advertisement
Wait, you mean something like this?

char *ptr = "string";
ptr = (char*)malloc(sizeof(char) * 16);

All you're doing is changing the pointer itself, it has nothing to do with what the pointer was pointing at.

Share this post


Link to post
Share on other sites
Pretty much yeah.

So no weird undefined behavior should happen. Of course now I don't have a pointer to the original string...better take care of that if I'm gonna need it later. It just seemed like really strange syntax that could potentially cause demons to erupt from my soda can.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!